LC 222 Count Complete Tree Nodes(M)
解题思路 优化的递归算法
public int countNodes(TreeNode root) {
if (root == null)
return 0;
TreeNode left = root;
TreeNode right = root;
int height = 0;
while(right != null){
left = left.left; //最左节点
right = right.right; //最右节点
//统计高度
height++;
}
if(left == null){
//完整二叉树
return (1<<height) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}Last updated