思路
- 平衡二叉樹定義:一個二叉樹每個節(jié)點的左右兩個子樹的高度差的絕對值不超過1延蟹。
- 分別求出其左右子樹的高度搀绣,然后如果差值小于等于1剩檀,則返回當(dāng)前二叉樹的高度惊搏,否則返回-1,表示已經(jīng)不是二叉平衡樹了。
- 如果最終結(jié)果返回 -1,則不是一個平衡二叉樹。
var isBalanced = function(root) {
const getDepth = (root) => {
if (!root) {
return 0
}
let leftDepth = getDepth(root.left)
if (leftDepth === -1) {
return -1
}
let rightDepth = getDepth(root.right)
if (rightDepth === -1) {
return -1
}
if (Math.abs(leftDepth - rightDepth) > 1) {
return -1
} else {
return 1 + Math.max(leftDepth, rightDepth)
}
}
return !(getDepth(root) === -1)
};
思路
var binaryTreePaths = function(root) {
let res = []
const getPath = (node, curPath) => {
if (!node.left && !node.right) {
curPath += node.val
res.push(curPath)
return
}
curPath += node.val + "->"
node.left && getPath(node.left, curPath)
node.right && getPath(node.right, curPath)
}
getPath(root, "");
return res
};
思路
- 關(guān)于左葉子定義:如果該節(jié)點的左節(jié)點不為空幢痘,該節(jié)點的左節(jié)點的左節(jié)點為空,該節(jié)點的左節(jié)點的右節(jié)點為空家破,則找到了一個左葉子颜说。
- 計算左葉子滿足條件:
if (root.left && !root.left.left && !root.left.right) { }
var sumOfLeftLeaves = function(root) {
let res = 0
const getLeaves = (root) => {
if (!root) {
return
}
if (root.left && !root.left.left && !root.left.right) {
res += root.left.val
}
getLeaves(root.left)
getLeaves(root.right)
}
getLeaves(root)
return res
};
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者