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

    Question:

    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.


    Tips:

    给定一个完全二叉树,求树中结点的个数。

    思路:

    完全二叉树的特性:完全二叉树:叶节点只能出现在最下层和次下层,并且最下面一层的结点都集中在该层最左边的若干位置的二叉树。即除了最后一层,前面所有层必须是满二叉树。这样我们就只要找到最后一层几个叶子节点就可以判断树中结点的数量。

    只有当左右子树高度想同的时候,才能知道该节点之前的树是满的。

    当左右子树高度不相等,采用递归的办法,来判断其做左右子树的高度是否相等。

    代码:

    //根据完全二叉树的特性 除最后一排 前面的树是满二叉树。
        public int countNodes(TreeNode root) {
            if (root == null)
                return 0;
            int ans=0;
            int left=getLeft(root);
            int right=getRight(root);
            if(left==right){
                return (1<<left)-1;
            }else
            return 1+countNodes(root.left)+countNodes(root.right);
        }
    
        private int getLeft(TreeNode root) {
            int h=0;
            while(root!=null){
                h++;
                root=root.left;
            }
            return h;
        }
        private int getRight(TreeNode root) {
            int h=0;
            while(root!=null){
                h++;
                root=root.right;
            }
            return h;
        }
  • 相关阅读:
    每日总结50
    每日总结49
    每日总结48
    每日总结47
    每日总结46
    每日总结45
    每日总结44
    每日总结42
    每日总结41
    每日总结39
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8555162.html
Copyright © 2011-2022 走看看