zoukankan      html  css  js  c++  java
  • 222. Count Complete Tree Nodes

    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;
        }
    }
  • 相关阅读:
    [BZOJ1006]神奇的国度
    配置ubuntu18.04
    数据库的基本操作
    关于排序的算法——桶排序
    关于TCP/IP协议的记录
    laravel学习历程
    装箱问题
    01背包
    数字三角形
    统计单词的个数
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10242309.html
Copyright © 2011-2022 走看看