My accepted Java solution using stack


  • 0
    A

    1.New a stack, and add the root.

    2.Do below steps while stack is not empty

    a.get stack's last element(mark as curNode)

    b.If(curNode.left!=null),add curNode.left to the stack,then let the curNode.left become null,return to step a.

    c.if(curNode.left==null) add curNode.val ,and remove curNode from stack.

    d.if(curNode.right!=null) add curNode.right to stack.

    public class Solution {
        
        public void setList(TreeNode root,ArrayList<Integer> res)
        {
            Stack<TreeNode> tree=new Stack<TreeNode>();
            tree.add(root);
            while(!tree.isEmpty())
            {
                TreeNode curNode=tree.lastElement();
                if(curNode.left!=null)
                {
                    tree.add(curNode.left);
                    curNode.left=null;
                    continue;
                }
                else
                {
                    res.add(curNode.val);
                    tree.pop();
                }
                if(curNode.right!=null)
                {
                    tree.add(curNode.right);
                }
            }
        }
        
        public List<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> res=new ArrayList<Integer>();
            if(root==null) return res;
            setList(root,res);
            return res;
        }
    }

Log in to reply
 

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