category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

222. Count Complete Tree Nodes

in complete binary tree.

approach

/**
* 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);
    }
}