Algorithms—104.Maximum Depth of Binary Tree

来源:互联网 发布:知乎2016 编辑:程序博客网 时间:2024/05/22 15:06

思路:分左右两路递归查询,查到某个节点下left和right都为null时返回,比较左右的值,取大的

/** * 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) {return 0;}if(root.left==null&&root.right==null){    return 1;}int left=-1;if(root.left!=null){   left=maxDepth(root.left)+1;}int right=-1;if(root.right!=null){   right=maxDepth(root.right)+1;}if(left==-1){    return right;}if(right==-1){    return left;}return Math.max(left, right);}}


耗时:316ms,测了2次,一次中游,一次勉强上游


0 0
原创粉丝点击