contains category wise problems(data structures, competitive) of popular platforms.
View the Project on GitHub mayankdutta/category-wise-problems
222. Count Complete Tree Nodes
last level
.left to right
manner.2^height - 1
./**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
int hr = 0;
int hl = 0;
TreeNode r = root;
TreeNode l = root;
while (r != null) {
r = r.right;
hr ++;
}
while (l != null) {
l = l.left;
hl ++;
}
if (hl == hr) {
return (1 << hl) - 1;
}
return 1 + countNodes(root.right) + countNodes(root.left);
}
}