Skip to content

Count Complete Tree Nodes

Tim_Gao edited this page Sep 15, 2016 · 2 revisions
  1. When talking about complete trees, this is the method that should try
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //private 
    public int countNodes(TreeNode root) {
        if (root == null){
            return 0;
        }
        int l = 0, r = 0;
        TreeNode crt = root;
        while (crt!=null){
            ++l;
            crt = crt.left;
        }
        crt  =root;
        while (crt!=null){
            ++r;
            crt = crt.right;
        }
        if (l == r){
            return (2<<(l-1))-1;
        } else {
            return countNodes(root.left) + countNodes(root.right)+1;
        }
    }
}

Clone this wiki locally