Day17 二叉树 part4
Leetcode110 Balanced Binary Tree
题目链接
求二叉树的深度 -> 从上到下: 可以用前序遍历
高度 -> 从下到上: 后序遍历
本题求的是高度(height-balanced), 显然后序遍历
- 确定函数: 传入当前node, 返回高度
为了标记左右子树高度差值超过1, 需要判断当前结点是否是平衡二叉树
是: 返回高度
否: 返回-1 - 明确终止条件
- 确定单层递归逻辑
class Solution {
public boolean isBalanced(TreeNode root) {
return (compare(root) != -1);
}
public int compare(TreeNode root){
if (root == null) return 0;
int left = compare(root.left);
if (left == -1) return -1;
int right = compare(root.right);
if (right == -1) return -1;
int result = 0;
if (Math.abs(left - right) > 1){
result = -1;
}
else{
result = 1 + Math.max(left,right);
}
return result;
}
}
Leetcode257 Binary Tree Paths
-
确定函数: 最终结果 ->
List<String> result
整数 ->List<Integer> path
void backtrack(TreeNode root, List<String> result, List<Integer> path)
-
确定终止条件: 找到叶子结点就应该停止 ->
root.left == null && root.right == null
注意!!return
-
单层递归逻辑
Notice: 回溯和递归是一一对应的,有一个递归,就要有一个回溯
// 判断要递归的结点是否为空, 是就不要递归了, 因为在终止条件里并没有进行root == null的判断
if (root.left != null) {
backtrack(root.left, result, path);
path.remove(path.size() - 1);
}
if (root.right != null){
backtrack(root.right, result, path);
path.remove(path.size() - 1);
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backtrack(root, result, path);
return result;
}
public void backtrack(TreeNode root, List<String> result, List<Integer> path){
path.add(root.val); // 最后一个结点也要加入到path中
if (root.left == null && root.right == null){
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++){
tmp.append(path.get(i)).append("->");
}
tmp.append(path.get(path.size()-1));
result.add(String.valueOf(tmp));
return;
}
if (root.left != null) {
backtrack(root.left, result, path);
path.remove(path.size() - 1);
}
if (root.right != null){
backtrack(root.right, result, path);
path.remove(path.size() - 1);
}
}
}
Leetcode404 Sum of Left Leaves
题目链接
本题在做的时候没有搞清怎么加做叶子的值, 反复了提交了多次, 应该要明确用结点的父节点来判断是不是做叶子, 当前结点本身无法判断 root.left != null && root.left.left == null && root.left.right == null
Method1 前序
class Solution {
int result = 0;
public int sumOfLeftLeaves(TreeNode root) {
traverse(root);
return result;
}
public void traverse(TreeNode root){
if (root == null) return;
if (root.left != null && root.left.left == null && root.left.right == null){
result += root.left.val;
}
traverse(root.left);
traverse(root.right);
}
}
Method2 后序
public int sumOfLeftLeaves(TreeNode root) {
int result = traverse(root);
return result;
}
public int traverse(TreeNode root){
if (root == null) return 0;
int left = traverse(root.left);
int right = traverse(root.right);
int mid = 0;
if (root.left != null && root.left.left == null & root.left.right == null){
mid += root.left.val;
}
return mid + left + right;
}