码迷,mamicode.com
首页 > 其他好文 > 详细

Count Complete Tree Nodes

时间:2017-06-30 12:24:20      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:leetcode   roo   war   script   else   count   root   logs   node   

https://leetcode.com/problems/count-complete-tree-nodes/#/description

http://www.cnblogs.com/EdwardLiu/p/5058570.html

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        int leftHeight = countLeft(root);
        int rightHeight = countRight(root);
        if (leftHeight == rightHeight) { //perfect binary tree
            return (1<<leftHeight)-1;
        }
        else return countNodes(root.left) + countNodes(root.right) + 1;
    }
    
    public int countLeft(TreeNode root) {
        int res = 0;
        while (root != null) {
            res++;
            root = root.left;
        }
        return res;
    }
    
    public int countRight(TreeNode root) {
        int res = 0;
        while (root != null) {
            res++;
            root = root.right;
        }
        return res;
    }
    
}

  

Count Complete Tree Nodes

标签:leetcode   roo   war   script   else   count   root   logs   node   

原文地址:http://www.cnblogs.com/apanda009/p/7098033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!