Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along, the longest path from the root node to the farthest leaf node.
We can do this problem with stack and iteration.
One stack<treenode> is used for node, and the other stack<integer> is used for depth value.
The code is as follows. ~
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public int maxDepth (TreeNode root) { stack<treenode> tree=new Stack<treenode > (); Stack<integer> value=new stack<integer> (); int max=0; if (root==null) { return 0; } Tree.push (root); Value.push (1); while (!tree.isempty ()) { TreeNode temp=tree.pop (); int Val=value.pop (); Max=math.max (max,val); if (temp.right!=null) { tree.push (temp.right); Value.push (val+1); } if (temp.left!=null) { tree.push (temp.left); Value.push (val+1); } } return max;} }
[Leetcode] Maximum Depth of Binary Tree