144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?

Solution:Stack

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution:Recursive

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution:Morris Traversal

思路:
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

Stack (regular)

class Solution {
    public List preorderTraversal(TreeNode root) {
       List list = new ArrayList<>();
        if(root == null) return list;
        Deque stack = new ArrayDeque<>();
        //Stack stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            list.add(cur.val);
            if(cur.right != null) stack.push(cur.right);
            if(cur.left != null) stack.push(cur.left);
        }
        return list;
    }
}

Stack (only right children are stored to the stack)

class Solution {
    public List preorderTraversal(TreeNode node) {
       List list = new LinkedList();
        Deque rights = new ArrayDeque();
        while(node != null) {
            list.add(node.val);
            if (node.right != null) {
                rights.push(node.right);
            }
            node = node.left;
            if (node == null && !rights.isEmpty()) {
                node = rights.pop();
            }
        }
        return list;
    }
}

Recursive:

class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new LinkedList();
        preHelper(root,pre);
        return pre;
    }
    public void preHelper(TreeNode root, List list) {
        if(root==null) return;
        list.add(root.val);
        preHelper(root.left, list);
        preHelper(root.right, list);
    }
}

你可能感兴趣的:(144. Binary Tree Preorder Traversal)