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

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

    我的代码:

    class Solution {
        int depth = 0;
        int con = 0;
    public:
        int TreeDepth(TreeNode* pRoot)
        {
            if(!pRoot)
                return con;
            depth++;
            if(pRoot->left == NULL && pRoot->right == NULL )
            {
                if(depth > con)
                    con = depth;
                return con;
            }
            if(pRoot->left)
            {
                TreeDepth(pRoot->left);
                depth--;
            }
            if(pRoot->right)
            {
                TreeDepth(pRoot->right);
                depth--;
            }
            return con;
        }
    };

    哇塞塞!别人的代码

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

    还有:

    import java.lang.Math;
    public class Solution {
        public int TreeDepth(TreeNode pRoot)
        {
            if(pRoot == null){
                return 0;
            }
            int left = TreeDepth(pRoot.left);
            int right = TreeDepth(pRoot.right);
            return Math.max(left, right) + 1;
        }
    }
  • 相关阅读:
    PAT 甲级 1128 N Queens Puzzle
    HDU 1995 R-汉诺塔V
    PAT L1-039 古风排版
    PAT L2-028 秀恩爱分得快
    ZOJ 2060 A-Fibonacci Again
    HDU 2079 选课时间
    HDU 1016 Prime Ring Problem
    理论相关概念原理
    单播字符、字符串收发
    OSAL的原理
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/8778582.html
Copyright © 2011-2022 走看看