Accepted Java Solution. No recursion.


  • 1
    P

    I use to stacks to store nodes and depths.

    public int maxDepth(TreeNode root) {
    	Stack<TreeNode> nodes = new Stack<TreeNode>();
    	Stack<Integer> depths= new Stack<Integer>();
    	nodes.push(root);
    	depths.push(1);
    	int max = 0;
    	
    	while(!nodes.isEmpty()) {
    		TreeNode node = nodes.pop();
    		int depth = depths.pop();
    		if (node == null) continue;
    		if (depth > max) max = depth;
    		nodes.push(node.left);
    		depths.push(depth+1);
    		nodes.push(node.right);
    		depths.push(depth+1);
    	}
    	
    	return max;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.