Java solution using stack running 240ms


  • 0
    S

    public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();
    if(root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode curr = root;
    int popped = 0;
    while(true){
    if(popped == 0 && curr.left != null) {
    stack.push(curr);
    curr = curr.left;
    }
    else{
    list.add(curr.val);
    if(curr.right != null){
    curr = curr.right;
    popped = 0;
    }
    else{
    if(stack.isEmpty()) break;
    curr = stack.pop();
    popped = 1;
    }
    }
    }
    return list;
    }
    }


Log in to reply
 

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