Maximum Depth of Binary Tree

mac2022-06-30  72

题目:

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.

 

 

题解:

与minimum代码几乎完全一样,只需要修改math.min为math.max

public class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } return getMin(root); } public int getMin(TreeNode root){ if (root == null) { return Integer.MIN_VALUE; } if (root.left == null && root.right == null) { return 1; } return Math.max(getMin(root.left), getMin(root.right)) + 1; } }

 

 用divide and conquer

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; } }

 

转载于:https://www.cnblogs.com/hygeia/p/4703660.html

最新回复(0)