leetcode 110
题目链接
判断平衡二叉树——左右子树高度差 ≤ 1 \le1 ≤1
思路:
- 后序遍历,求左右子树高度
- 用
-1
表示高度差大于1,非AVL树了
class Solution {
public boolean isBalanced(TreeNode root) {
int res = postOrder(root);
return res == -1 ? false : true;
}
public int postOrder(TreeNode root) {
if (root == null)
return 0;
int leftDepth = postOrder(root.left);
if (leftDepth == -1)
return -1;
int rightDepth = postOrder(root.right);
if (rightDepth == -1)
return -1;
if (Math.abs(leftDepth - rightDepth) <= 1)
return Math.max(leftDepth, rightDepth) + 1;
else
return -1;
}
}
leetcode 257
题目链接
二叉树路径:从根到叶子节点
思路:
- 找所有的路径——一定是前序遍历
- 需要回溯:找到一条路径后,回退到根节点,找另外一条路径
- 递归法
- 终止条件确认:找到叶子节点(左右孩子均为
null
) - 终止处理逻辑:把
path
加入结果中 - 每次递归完都需要回溯处理
- 终止条件确认:找到叶子节点(左右孩子均为
递归法代码,体会回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if (root == null)
return res;
pretraversal(root, path, res);
return res;
}
public void pretraversal(TreeNode node, List<Integer> path, List<String> res) {
path.add(node.val); //前序遍历,中
if (node.left == null && node.right == null) { //leaf
StringBuilder p = new StringBuilder();
for (int i = 0; i < path.size() - 1; ++i)
p.append(path.get(i) + "->");
p.append(path.get(path.size() - 1));
res.add(p.toString());
return;
}
if (node.left != null) {
pretraversal(node.left, path, res);
path.remove(path.size() - 1);
}
if (node.right != null) {
pretraversal(node.right, path, res);
path.remove(path.size() - 1);
}
}
}
leetcode 404
题目链接
左叶子之和
思路:
- 左叶子:叶子节点,是父节点的左孩子
自己写的代码,用的递归法,前序遍历方式?(也可以说是后序,中节点不做处理)
class Solution {
int res = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null)
return 0;
pretraversal(root);
return res;
}
public void pretraversal(TreeNode node) {
if (node == null)
return;
if (node.left != null) {
if (node.left.left == null && node.left.right == null)
res += node.left.val; //node.left is left leaf
pretraversal(node.left);
}
if (node.right != null) {
pretraversal(node.right);
}
}
}