222.完全二叉树的节点个数
自己做没想出来完全二叉树这个条件怎么利用,直接递归遍历了
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return countNodes(root.left)+countNodes(root.right)+1;
}
}
但看了题解,如果判断子树为满二叉树,可以直接套公式
关键在于怎么判断满二叉树:只需要一直向左和一直向右的深度一样
优化后的代码如下(加入满二叉树的情况)
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int l = 1, r = 1;
while(left != null) {
left = left.left;
l++;
}
while(right != null){
right = right.right;
r++;
}
if (l == r) return (int)Math.pow(2,l) -1;
return countNodes(root.left)+countNodes(root.right)+1;
}
}
110.平衡二叉树
先去看了下二叉树里面的高度和深度
高度是到叶子结点的距离,向上增长,用后序遍历来向上返回递归结果
深度是到根节点的距离 ,向下增长,用前序遍历递归一直向下走
本题的递归套路如下:
1.传入节点,返回高度
2.终止条件:传入的节点为空,此时高度为0,return 0
3.递归部分:采用后序遍历,先左右分别判断子树有没有-1标记,再对当前节点判断是否平衡,如果不平衡就return -1, 平衡就return节点的真实高度
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
public int height(TreeNode root) {
if (root == null) return 0;
int l = height(root.left);
if (l == -1) return -1;
int r = height(root.right);
if (r == -1) return -1;
if (Math.abs(l-r) > 1) return -1;
return Math.max(l, r) + 1;
}
}
257. 二叉树的所有路径
从根节点到叶节点,采用前序遍历
结束条件为找到叶子结点
前序遍历中先把当前值加入path,当不是叶子结点时,在左右遍历的时候递归完进行回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
List<Integer> path = new ArrayList<>();
travel(root,path,res);
return res;
}
void travel(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){
travel(root.left, path, res);
path.remove(path.size()-1);
}
if (root.right != null){
travel(root.right, path, res);
path.remove(path.size()-1);
}
}
}