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

    【问题】输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

    【思路】递归解法:一般和深度有关的我们都可以使用dfs算法,然后使用一个res用于记录深度,每次递归到叶节点,将res和max进行比较,将最大的值存入max变量中,结束递归!这样我们就可以找到每一条路径深度最大的哪一个路径了!

    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot){
            return pRoot ? max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1 :0;
        }
    };

    第二种使用非递归的思路,我们都知道层次遍历,每次都是遍历完上一层才会去下一层遍历。因此,我们可以对层次遍历加以修改!设置一个depth变量,如果遍历完一层,则让depth++。层次遍历需要队列的辅助!

    /*
    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)
        {
            if(pRoot == nullptr) return 0;
            queue<TreeNode*> que;
            que.push(pRoot);
            int depth = 0;
            while(!que.empty()){
                int size = que.size();
                depth++;
                while(size--){
                    TreeNode* tmp = que.front();
                    que.pop();
                    if(tmp->left) que.push(tmp->left);
                    if(tmp->right) que.push(tmp->right);
                }
            }
            return depth;
        }
    };
  • 相关阅读:
    Spring事务管理(详解+实例)
    DRUID连接池的实用 配置详解
    spring配置c3p0
    Spring使用JdbcTemplate实现对数据库操作
    spring整合web 项目
    2018美团JAVA面试问题与总结
    Mybatis中的update动态SQL语句
    去除文件夹左下角的问号
    spring的aop实现原理
    Spring的bean管理注解和配置文件混合使用
  • 原文地址:https://www.cnblogs.com/zhudingtop/p/11385852.html
Copyright © 2011-2022 走看看