关闭

Count Complete Tree Nodes

标签: TreeBinary Search
275人阅读 评论(0) 收藏 举报
分类:
/**
 * 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 left = leftHeight(root);
        int right = rightHeight(root);
        if (left == right) {
            return (2<<left) - 1;
        } else {
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
    }
    private int leftHeight(TreeNode node) {
        TreeNode left = node.left;
        int height = 0;
        while (left != null) {
            left = left.left;
            height++;
        }
        return height;
    }
    private int rightHeight(TreeNode node) {
        TreeNode right = node.right;
        int height = 0;
        while (right != null) {
            right = right.right;
            height++;
        }
        return height;
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27658次
    • 积分:2364
    • 等级:
    • 排名:第16342名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条