144. Binary Tree Preorder Traversal

Description

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

tree

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

Solution

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List preorder = new LinkedList<>();
        preorderTraversalRecur(root, preorder);
        return preorder;
    }
    
    public void preorderTraversalRecur(TreeNode root, List preorder) {
        if (root == null) {
            return;
        }
        
        preorder.add(root.val);
        preorderTraversalRecur(root.left, preorder);
        preorderTraversalRecur(root.right, preorder);
    }
}

Iterative using Stack, time O(n), space O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List preorder = new LinkedList<>();
        if (root == null) {
            return preorder;
        }
        
        Stack stack = new Stack<>();
        stack.push(root);
        
        while (!stack.empty()) {
            TreeNode curr = stack.pop();
            preorder.add(curr.val);
            if (curr.right != null) stack.push(curr.right);
            if (curr.left != null) stack.push(curr.left);
        }
        
        return preorder;
    }
}

Common solution, time O(n), space O(h)

preorder, inorder, postorder的通用写法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new LinkedList<>();
        Stack stack = new Stack<>();
        TreeNode p = root;
        
        while (!stack.empty() || p != null) {
            if (p != null) {
                stack.push(p);
                list.add(p.val);        // add before going to children
                p = p.left;             // go left
            } else {
                p = stack.pop().right;  // go right
            }
        }
        
        return list;
    }
}

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