题目描述:
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.
思路:
求二叉树的最大深度。递归和迭代两种解法。
递归:如果根节点是null,则返回0
否则返回左子树或者右子树的深度+1
迭代:未做。
/*
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
*/
1 public class Solution104 { 2 public int maxDepth(TreeNode root) { 3 if(root == null) return 0; 4 return Math.max(maxDepth(root.left),maxDepth(root.right))+1; 5 } 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 Solution104 solution104 = new Solution104(); 9 TreeNode root = new TreeNode(1); 10 root.left = new TreeNode(2); 11 root.right = new TreeNode(2); 12 root.left.left = new TreeNode(3); 13 root.left.right = new TreeNode(4); 14 root.right.left = new TreeNode(4); 15 //root.right.right = new TreeNode(3); 16 root.right.left.left = new TreeNode(4); 17 System.out.println(solution104.maxDepth(root)); 18 } 19 20 }