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.
Java code:
public int maxDepth(TreeNode root) { if(root == null) return 0; int max = 0; Queuetmp = new LinkedList (); tmp.add(root); while(!tmp.isEmpty()){ max++; int size = tmp.size(); for(int i = 0; i < size; i++){ TreeNode node = tmp.poll(); if(node.left != null) tmp.add(node.left); if(node.right != null) tmp.add(node.right); } } return max; }
No comments:
Post a Comment