zoukankan      html  css  js  c++  java
  • 二叉树的深度

    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot)
        {
        	int len=0;
            if(pRoot==NULL)	return 0;
            while(pRoot->val) {
                len++;
                pRoot=pRoot->left;
            }
            return len;
        }
    };
    

      

    不通过
    您的代码已保存
    段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
     
     
    递归思路!
    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot)
        {
        	int len=0;
            if(pRoot==NULL)	return 0;
            return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
        }
    };
    
    //由于每个节点都需要判断下面左右节点是不是存在,若存在则要继续递归往下判断。所有需要调用两次本体函数
    //一个摸左边,一个摸右边。 但是每次摸完,我们要的是最深的,所以我们返回左右两边最大的那个值。
    //那么值是怎么来的? 递归是有外向内,再由内向外。 这里由上到下,再由下到上。一步一步上去,每递归一次,层数加1.则最下面返回0就好了

    bfs的解法 思路新颖巧妙。层序遍历到最深!

    int TreeDepth(TreeNode* pRoot)
        {
         queue<TreeNode*> q;
            if(!pRoot) return 0;
            q.push(pRoot);
            int level=0;
            while(!q.empty()){
                int len=q.size();
                level++;
                while(len--){
                    TreeNode* tem=q.front();
                    q.pop();
                    if(tem->left) q.push(tem->left);
                    if(tem->right) q.push(tem->right);
                }
            }
            return level;
        }
    

      

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    基于摸板匹配的目標跟蹤算法
    spoj 2713 Can you answer these queries IV
    zoj 3633 Alice's present
    hdu 3642 Get The Treasury
    poj 1195 Mobile phones
    poj 2760 End of Windless Days
    zoj 3540 Adding New Machine
    spoj 1716 Can you answer these queries III
    spoj 1043 Can you answer these queries I
    spoj 2916 Can you answer these queries V
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7412281.html
Copyright © 2011-2022 走看看