Count Complete Tree Nodes
Thoughts
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int leftHeight(TreeNode root) {
if (root == null) {
return 0;
}
return leftHeight(root.left) + 1;
}
private int rightHeight(TreeNode root) {
if (root == null) {
return 0;
}
return rightHeight(root.right) + 1;
}
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int left = leftHeight(root);
int right = rightHeight(root);
if (left == right) {
return (1 << left) - 1;
} else {
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
}Analysis
Ver.2
PreviousConstruct Binary Tree from Inorder and Postorder TraversalNextPopulating Next Right Pointers in Each Node
Last updated