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;
        }
    

      

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    bash组织成树数据结构
    statickeyword于C和C++用法
    POJ2239 Selecting Courses【二部图最大匹配】
    MVC过滤器的详细讲解和示范样本
    hdoj 2602 Bone Collector 【01背包】
    下的生产环境was重新启动不同意,怎么做?
    Qt Model/View 的简单说明
    View与Model绑定注意事项 (视图无数据显示)
    Qt Delgate的使用 简单说明
    QAbstractTableModel中的data()到底执行几遍???
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7412281.html
Copyright © 2011-2022 走看看