day15:二叉树part4,平衡二叉树,二叉树所有路径
110.平衡二叉树
求高度只能后序遍历
(根节点高度等于树的最大深度)
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
private 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;
return Math.abs(leftHeight - rightHeight) > 1 ? -1 : 1 + Math.max(leftHeight, rightHeight);
}
}
257.二叉树的所有路径
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) return ans;
// 回溯记录每一条路径
List<Integer> path = new ArrayList<>();
dfs(root, path, ans);
return ans;
}
private void dfs(TreeNode node, List<Integer> path, List<String> ans) {
// 递归终止条件,前序遍历先把根节点加入path
path.add(node.val);
// 遇到叶子节点终止
if (node.left == null && node.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++) {
sb.append(path.get(i) + "->");
}
sb.append(path.get(path.size() - 1));
ans.add(sb.toString());
return;
}
// 单层递归
if (node.left != null) {
dfs(node.left, path, ans);
path.remove(path.size() - 1);
}
if (node.right != null) {
dfs(node.right, path, ans);
path.remove(path.size() - 1);
}
}
}
404.左叶子之和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
// 有左叶子
if (root.left != null && root.left.left == null && root.left.right == null) {
return root.left.val + sumOfLeftLeaves(root.right);
}
// 没有左叶子
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}