Java solution using stack


  • 1
    W
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            if(root == null)
                return result;
            MyStack s = new MyStack();
            s.push(root);
            TreeNode cur = root.left;
            
            while(!s.empty() || cur != null) {
                while(cur != null) {
                    s.push(cur);
                    cur = cur.left;
                }
                cur = s.pop();
                result.add(cur.val);
                cur = cur.right;
            }
            return result;
        }
    }
    
    class MyStack {
        Node head;
        
        void push(TreeNode t) {
            Node node = new Node(t);
            node.next = head;
            head = node;
        }
        
        TreeNode pop() {
            TreeNode result = head.payload;
            head = head.next;
            return result;
        }
        
        boolean empty() {
            return head == null;
        }
    }
    
    class Node {
        TreeNode payload;
        Node next;
        
        public Node(TreeNode payload) {
            this.payload = payload;
        }
    }

Log in to reply
 

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