110. 平衡二叉树
题目链接:110. 平衡二叉树
思路: 递归计算左子树和右子树的高度,后序遍历位置判断左右子树的高度差,并计算root的高度。
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = getHeight(root.left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(root.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
}
总结:
257. 二叉树的所有路径
题目链接:257. 二叉树的所有路径
思路: 这题用到回溯。求所有根节点到叶子节点的路径,遍历一遍二叉树肯定可以搞定,遍历到叶子节点的时候想办法把路径生成出来就行了。path代表当前路径上的节点,res代表所有路径,每遍历到一个节点,将它加入path,出这个节点的时候,再移出path。当遍历到叶子节点的时候,将path加入res。
class Solution {
LinkedList<String> path = new LinkedList<>();
LinkedList<String> res = new LinkedList<>();
public List<String> binaryTreePaths(TreeNode root) {
traverse(root);
return res;
}
public void traverse(TreeNode root) {
if (root == null) {
return;
}
path.add(root.val + "");
if (root.left == null && root.right == null) {
res.add(String.join("->", path));
path.removeLast();
return;
}
traverse(root.left);
traverse(root.right);
path.removeLast();
}
}
总结:
404. 左叶子之和
题目链接:404. 左叶子之和
思路:
遍历一遍二叉树,然后找到那些左叶子节点,注意左叶子节点的判断条件,if (root.left != null && root.left.left == null && root.left.right == null)。
我的代码:
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
// if (root.left == null && root.right == null) {
// return 0;
// }
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
sumOfLeftLeaves(root.left);
sumOfLeftLeaves(root.right);
return sum;
}
}
总结: