1.完全二叉树节点的数量
前/中/后序遍历:
public int countNodes(TreeNode root) {
if(root == null) return 0;
int ll = countNodes(root.left); //左
int rr = countNodes(root.right); //右
int gg = ll + rr + 1; //根
return gg;
}
使用完全二叉树特性:判断子树是否为满二叉树,可以减少节点的遍历(不用遍历中间的节点,只遍历两边)
public int countNodes(TreeNode root){
if(root == null) return 0;
//是否为满二叉树
TreeNode left = root.left;
int left_height = 0;
TreeNode right = root.right;
int right_height = 0;
while(left != null){
left_height++;
left = left.left;
}
while (right != null){
right_height++;
right = right.right;
}
//满二叉树
if(left_height == right_height)
return (2 << left_height) - 1; //2 << 0表示2的1次方
int ll = countNodes(root.left); //左
int rr = countNodes(root.right); //右
int gg = ll + rr + 1; //根
return gg;
}
2.平衡二叉树
后序遍历:先计算左右子树的高度,判断是否相差大于1
public boolean isBalanced(TreeNode root){
if(getHeight(root) == -1) return false;
return true;
}
public int getHeight(TreeNode node){
if(node == null) return 0;
int ll = getHeight(node.left); //左
if(ll == -1) return -1; //左子树不为平衡树,返回-1
int rr = getHeight(node.right); //右
if(rr == -1) return -1; //右子树不为平衡树,返回-1
if(Math.abs(ll-rr) > 1) return -1; //左右孩子相差超过1,返回-1
int gg = Math.max(ll, rr) + 1; //根
return gg;
}
3.二叉树的所有路径
前序遍历:
List<String> res;
public List<String> binaryTreePaths(TreeNode root) {
res = new ArrayList<>();
if(root == null) return res;
if(root.left == null && root.right == null) {
res.add(root.val+"");
return res;
}
dfs(root, ""+root.val);
return res;
}
public void dfs(TreeNode node, String s){
//叶子节点
if(node.left == null && node.right == null){
//s = s+"->"+node.val;
res.add(s);
return;
}
if(node.left != null) dfs(node.left, s+"->"+node.left.val);
if(node.right != null) dfs(node.right, s+"->"+node.right.val);
}