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

    https://leetcode.com/problems/count-complete-tree-nodes/

    宽度优先搜索方法,超时!!

    /**
     * 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) {
            
            int height=1;
            if(root==NULL)
                return 0;
            TreeNode * temp=root;
            stack<TreeNode *> s1;
            while(temp!=NULL)
            {
                height++;
                s1.push(temp);
                temp=temp->right;
            }
            int count=(int)(pow(2,height)-1);
            bool flag=0;
            int len=1;
            int leftVal=0;
            int rightVal=0;
            while(!s1.empty())
            {
                len++;
                TreeNode * temp=s1.top();
                s1.pop();
                if(right==0)
                    rightVal=getCount(temp->right);
                else
                    rightVal=leftVal+right+1;
                leftVal=getCount(temp->left);
                if(leftVal!=rightVal)
                    break;
            }
            int lack=(int)(pow(2,len)-1-(leftVal+rightVal+1));
            int res=count-lack;
            return res;
            
        }
        int getCount(TreeNode * node)
        {
            if(node==NULL)
                return 0;
            int res=0;
            queue<TreeNode *> q;
            q.push(node);
            while(!q.empty())
            {
                res++;
                TreeNode * temp=q.front();
                q.pop();
                if(temp->left!=NULL)
                    q.push(temp->left);
                if(temp->right!=NULL)
                    q.push(temp->right);
            }
            return res;
        }
    };
  • 相关阅读:
    psi
    firefox修改语言
    automapper
    堆喷图解
    脱壳系列_0_FSG壳_详细版
    脱壳系列_1_UPX壳_详细版
    算法01-最大子数组详解
    逆向MFC程序
    如何执行shell命令
    Unity之流光效果
  • 原文地址:https://www.cnblogs.com/aguai1992/p/4780452.html
Copyright © 2011-2022 走看看