Count Complete Tree Nodes

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

阅读更多
文章标签: Tree Binary Search
个人分类: Leetcode 刷题
上一篇Minimum Size Subarray Sum
下一篇Min Stack
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭