美文网首页
222. Count Complete Tree Nodes

222. Count Complete Tree Nodes

作者: FlynnLWang | 来源:发表于2016-12-27 04:01 被阅读0次

Question

Given a complete binary tree, count the number of nodes.

Code

/**
 * 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 l = getLeft(root), r = getRight(root);
        if (l == r) return (2 << (l - 1)) - 1;
        return 1 + countNodes(root.left) + countNodes(root.right);
    }
    
    public int getLeft(TreeNode node) {
        int count = 1;
        while (node.left != null) {
            count++;
            node = node.left;
        }
        return count;
    }
    
    public int getRight(TreeNode node) {
        int count = 1;
        while (node.right != null) {
            count++;
            node = node.right;
        }
        return count;
    }
}

Solution

如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是complete binary tree. 而 complete binary tree的节点数, 可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right) + 1.

相关文章

网友评论

      本文标题:222. Count Complete Tree Nodes

      本文链接:https://www.haomeiwen.com/subject/ddusvttx.html