144. Binary Tree Preorder Traversal

  1. Visit and Push all the way left
  2. cur = pop()
  3. cur = cur.right (then go back to 1 and continue)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> returnList = new ArrayList<Integer>();
        if(root == null)
        {
            return returnList;
        }
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode cur = root;
        while(cur!=null || !stack.isEmpty()){
            while(cur!=null)
            {
                returnList.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        return returnList;
    }
}

results matching ""

    No results matching ""