美文网首页
leetcode的每天一题更新(Maximum Depth of

leetcode的每天一题更新(Maximum Depth of

作者: 今天是晴天 | 来源:发表于2017-04-20 18:11 被阅读0次

    题目:给一个二叉树,返回这棵树的高度。
    解题思路:这个题目就是典型的数据结构的题目,自己的基础不够扎实,所以想了很久才想出一些思路,肯定是用递归实现是最简单的,但是想了半天只有一点点头绪,最关键那里怎么都没想明白,到底应该怎么返回才能表示,今天时间紧迫只能翻开自己的数据结构的数,看完以后恍然大悟,说到底返回的值不用怎么变化只是子树加一再判断左右哪边大再返回哪一边,数据结构要再学一遍了,以前学的朦朦懂懂的,现在看到很多都感觉比较清晰了,附上代码:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int maxDepth(TreeNode root) {
            if(root!=null){
                int lDepth =maxDepth(root.left);
                int rDepth =maxDepth(root.right);
                return 1+(lDepth > rDepth ? lDepth : rDepth);
            }else{
                return 0;
            }
        }
    }
    

    看了一下最快捷的方法也是这个。

    相关文章

      网友评论

          本文标题:leetcode的每天一题更新(Maximum Depth of

          本文链接:https://www.haomeiwen.com/subject/azilzttx.html