110.平衡二叉树 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。(前序遍历)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。(后序遍历)
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. 二叉树的所有路径 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
从根节点到叶子的路径,所以需要前序遍历
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if(root == null) {
return res;
}
List<Integer> path = new ArrayList<>();
traversal(root, path, res);
return res;
}
private void traversal(TreeNode root, List<Integer> path, List<String> res) {
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++) {
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size() - 1));
res.add(sb.toString());
return;
}
if (root.left != null) {
traversal(root.left, path, res);
path.remove(path.size() - 1);
}
if (root.right != null) {
traversal(root.right, path, res);
path.remove(path.size() - 1);
}
}
}
404.左叶子之和 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int leftValue = sumOfLeftLeaves(root.left);
int rightValue = 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 + leftValue + rightValue;
return sum;
}
}