加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

222. Count Complete Tree Nodes - Medium

发布时间:2020-12-14 05:16:10 所属栏目:大数据 来源:网络整理
导读: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 completely filled,and all nodes in the last level are as f

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 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.

Example:

Input: 
    1
   /   2   3
 /   /
4  5 6

Output: 6

?

思路:比较左右子树深度是否相等,如果相等,返回2 ^ h - 1;不等则对左右子节点递归。因为是complete tree,求左右子树的深度只要一直往左/右走并计数即可

time: O(logn * logn),space: O(n) worst case,O(logn) best case

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftDepth = depth(root,true);
        int rightDepth = depth(root,false);
        if(leftDepth == rightDepth) {
            return (1 << leftDepth) - 1;
        } else {
            return 1 + countNodes(root.left) + countNodes(root.right);
        }
    }
    
    public int depth(TreeNode node,boolean isLeft) {
        int depth = 0;
        while(node != null) {
            node = isLeft ? node.left : node.right;
            depth++;
        }
        return depth;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读