LeetCode110 平衡二叉树
题目链接:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html代码:
public class code110 {
public boolean isBalanced(TreeNode root) {
if (getHeight(root) == -1) {
return false;
}
return true;
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if (leftHeight == -1) {
return -1;
}
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return 1 + Math.max(leftHeight, rightHeight);
}
}
遍历顺序依然为后序,如果左右孩子不为平衡二叉树,直接返回-1,如果当前节点的左右孩子高度差大于1,直接返回-1
LeetCode257 二叉树的所有路径
public class code257 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
getPath(root, "", res);
return res;
}
private void getPath(TreeNode root, String path, List<String> res) {
if (root == null) {
return;
}
// 如果是叶子节点,将路径添加到结果集中
if (root.left == null && root.right == null) {
res.add(path + root.val);
return;
}
// 如果不是叶子节点,遍历左右孩子
getPath(root.left, path + root.val + "->", res);
getPath(root.right, path + root.val + "->", res);
}
}
遍历顺序为前序遍历
LeetCode404 左叶子之和
题目链接:https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html代码:
public class code404 {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int leftSum = sumOfLeftLeaves(root.left); // 左
int rightSum = sumOfLeftLeaves(root.right); // 右
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int sum = midValue + leftSum + rightSum;
return sum;
}
}
遍历顺序为后序遍历,注意左叶子的判定条件