一、平衡二叉树
递归法,后序
高度只能从下往上找,所以必须用后序遍历,左右中
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function (root) {
function getDepth(root) {n
if (!root) {
return 0
}
let leftHeight = getDepth(root.left)
let rightHeight = getDepth(root.right)
if (leftHeight === -1 || rightHeight === -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1
}
return Math.max(leftHeight, rightHeight) + 1
}
return getDepth(root) !== -1
};
二、二叉树的所有路径
求根节点到叶子节点的路径,所以需要前序遍历
回溯思路,记录的路径需要回退再进入另一个路径,递归和回溯是相伴相生的,有一次递归就需要一次回溯
递归法
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
let result = []
function getPath(node, curPath = '') {
if(!node.left && !node.right) {
result.push(curPath + node.val)
return
}
curPath += node.val + '->'
node.left && getPath(node.left, curPath)
node.right && getPath(node.right, curPath)
}
getPath(root)
return result
};
迭代法
var binaryTreePaths = function(root) {
let result = []
let paths = ['']
let stack = [root]
while(stack.length) {
let node = stack.pop()
let path = paths.pop()
if(!node.left && !node.right) {
result.push(path + node.val)
continue
}
path += node.val + '->'
if(node.right) {
paths.push(path)
stack.push(node.right)
}
if(node.left) {
paths.push(path)
stack.push(node.left)
}
}
return result
};
三、左叶子之和
左叶子节点的定义:节点A的左节点不为空,且左节点的左右子节点都为控,叶子节点
递归法
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumOfLeftLeaves = function(root) {
function getSum(node) {
if(!node) {
return 0
}
let midVal = 0
if(node.left && !node.left.left && !node.left.right) {
midVal += node.left.val
}
let leftVal = getSum(node.left)
let rightVal = getSum(node.right)
return midVal + leftVal + rightVal
}
return getSum(root)
};
迭代法
var sumOfLeftLeaves = function(root) {
let stack = [root]
let sum = 0
while(stack.length) {
let node = stack.pop()
if(node.left && !node.left.left && !node.left.right) {
sum += node.left.val
}
node.right && stack.push(node.right)
node.left && stack.push(node.left)
}
return sum
};