public int maxDepth(TreeNode root) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if (root == null)
			return 0;

		Stack<TreeNode> paths = new Stack<TreeNode>();
		int depth = 1;
		int maxDepth = 0;

		paths.push(root);
		while (!paths.isEmpty()) {
			TreeNode node = paths.peek();
			while (node.left != null) {
				node = node.left;
				paths.push(node);
				depth++;

			}

			if(node.right != null){
                paths.push(node.right);
                depth ++;
            }else{
                maxDepth = Math.max(maxDepth, depth);
                TreeNode pNode = paths.pop();
                depth --;
                TreeNode tNode;
                while(!paths.isEmpty() && (pNode == (tNode=paths.peek()).right || (pNode == tNode.left && tNode.right == null))){
                    pNode = paths.pop();
                    depth --;
                }

                if(!paths.isEmpty()){
                    paths.push(paths.peek().right);
                    depth ++;
                }

            }
		}

		return maxDepth;
	}