LeetCode-探索-初级算法-树-1. 二叉树的最大深度(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-树-1. 二叉树的最大深度(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 二叉树的最大深度
  • 语言:java

  • 思路:利用递归思想,树最大深度就是左子树和右子树的最大深度+1;而终止条件就是如果当前树是空,返回0;

  • 代码(1ms):

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null)
                return 0;
            int depth = 0,left = 0,right = 0;
            left = maxDepth(root.left)+1;
            right = maxDepth(root.right)+1;
            depth = left > right?left:right;
            return depth;
        }
    }
    
  • 参考代码(0ms):

    class Solution {
        public int maxDepth(TreeNode root) {
            return root==null? 0 : Math.max(maxDepth(root.left),maxDepth(root.right))+1;
        }
    }
    
  • 参考后重写(1ms):很迷,基本是一样的,居然还慢了,不过是rootnull变成了nullroot,涉及优化问题,暂不考虑

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            return null==root?0:Math.max(maxDepth(root.left),maxDepth(root.right))+1;
        }
    }
    
发布了60 篇原创文章 · 获赞 6 · 访问量 5538

猜你喜欢

转载自blog.csdn.net/Ashiamd/article/details/102263302