Maximum Depth of Binary Tree
问题:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node
思路:
递归
我的方法:
public class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0 ; if(root.left == null && root.right == null) return 1 ; else { int left = maxDepth(root.left) ; int right = maxDepth(root.right) ; return Math.max(left , right) + 1 ; } } }
别人方法:
public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); return Math.max(left, right) + 1; } }
学习之处:
冗余判断了 root.left == null && root.right == null 没有必要进行判断
if(root==null) return 0;
return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));