Question:
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.
Solution:
Using recursion:
public class Solution { public int maxDepth(TreeNode root) { if(root != null){ return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }else{ return 0; } }}
Using iteration:
Using BFS calculate the tree length
public class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } int length = 0; ArrayList<TreeNode> treeLev = new ArrayList<TreeNode>(); treeLev.add(root); while(treeLev != null && !treeLev.isEmpty()){ ArrayList<TreeNode> treeLev2 = new ArrayList<TreeNode>(); for(TreeNode node1 : treeLev){ if(node1.left != null){ treeLev2.add(node1.left); } if(node1.right != null){ treeLev2.add(node1.right); } } treeLev = new ArrayList<TreeNode>(); treeLev.addAll(treeLev2); length ++ ; } return length; }}