资讯专栏INFORMATION COLUMN

222. Count Complete Tree Nodes

callmewhy / 944人阅读

摘要:题目解答学了的方法哈哈这里是从开始算起,所以求出来的结果是实际是这一步很巧妙,把根结点加上,然后分治左结点和右结点,如果是叶子结点,在中就返回

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

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

解答:

public class Solution {
    //学了enum的方法哈哈
    public enum Direction {
        LEFT, RIGHT
    }
    
    public int getDepth(TreeNode root, Direction dir) {
        int depth = 0;
        //这里是从root开始算起,所以求出来的结果是实际depth + 1
        while (root != null) {
            depth++;
            if (dir == Direction.LEFT) {
                root = root.left;
            } else {
                root = root.right;
            }
        }
        return depth;
    }
    
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = getDepth(root, Direction.LEFT);
        int rightDepth = getDepth(root, Direction.RIGHT);
        
        if (leftDepth == rightDepth) {
            //1 << leftDepth是2^(leftDepth)
            return (1 << leftDepth) - 1;
        } else {
            //这一步很巧妙,把根结点加上,然后分治左结点和右结点,如果是叶子结点,在countNodes中就返回1
            return 1 + countNodes(root.left) + countNodes(root.right);
        }
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64885.html

相关文章

  • leetcode222. Count Complete Tree Nodes

    摘要:题目要求计算一个完全二叉树的节点个数。其中完全二叉树是指除了最后一行,其余的每一行都必须是满节点的树。当然超时啦思路二讲道理的递归思路一很明显没有充分利用这是一颗完全二叉树的条件。 题目要求 Given a complete binary tree, count the number of nodes. Definition of a complete binary tree fro...

    crossoverJie 评论0 收藏0
  • [LeetCode] 222. Count Complete Tree Nodes

    Problem Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completel...

    kamushin233 评论0 收藏0
  • [Leetcode] Count Complete Tree Nodes 统计完全树节点数

    摘要:如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。注意这里在左节点递归时代入了上次计算的左子树最左深度减,右节点递归的时候代入了上次计算的右子树最右深度减,可以避免重复计算这些深度做的幂时不要用,这样会超时。 Count Complete Tree Nodes Given a complete binary tree, count the number of nod...

    animabear 评论0 收藏0
  • [LeetCode] 501. Find Mode in Binary Search Tree

    Problem Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node c...

    NikoManiac 评论0 收藏0
  • [LeetCode] Path Sum (I & II & III)

    摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...

    张金宝 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<