zoukankan      html  css  js  c++  java
  • 222 Count Complete Tree Nodes 完全二叉树的节点个数

    给出一个完全二叉树,求出该树的节点个数。
    完全二叉树的定义如下:
    在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含1~ 2h 个节点。
    详见:https://leetcode.com/problems/count-complete-tree-nodes/description/

    Java实现:

    分别找出以当前节点为根节点的左子树和右子树的高度并对比,如果相等,则说明是满二叉树,直接返回节点个数,如果不相等,则节点个数为左子树的节点个数加上右子树的节点个数再加1(根节点),其中左右子树节点个数的计算可以使用递归来计算。

    /**
     * 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 hl=0;
            int hr=0;
            TreeNode left=root;
            TreeNode right=root;
            while(left!=null){
                ++hl;
                left=left.left;
            }
            while(right!=null){
                ++hr;
                right=right.right;
            }
            if(hl==hr){
                return (int)(Math.pow(2,hl)-1);
            }
            return 1+countNodes(root.left)+countNodes(root.right);
        }
    }
    

    C++实现:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int countNodes(TreeNode* root) {
            if(root==nullptr)
            {
                return 0;
            }
            int hl=0,hr=0;
            TreeNode* left=root,*right=root;
            while(left)
            {
                ++hl;
                left=left->left;
            }
            while(right)
            {
                ++hr;
                right=right->right;
            }
            if(hl==hr)
            {
                return pow(2,hl)-1;
            }
            return 1+countNodes(root->left)+countNodes(root->right);
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/4567827.html

  • 相关阅读:
    451. Sort Characters By Frequency
    424. Longest Repeating Character Replacement
    68. Text Justification
    44. Wildcard Matching
    160. Intersection of Two Linked Lists
    24. Swap Nodes in Pairs
    93. 递归实现组合型枚举
    98. 分形之城
    97. 约数之和
    96. 奇怪的汉诺塔
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8748878.html
Copyright © 2011-2022 走看看