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?

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if (root == null){
            return result;
        }
        TreeNode t = null;
        stack.push(root);
        while (!stack.empty()&&(t = stack.pop())!=null){
            result.add(t.val);
            if (t.right != null){
                stack.add(t.right);
            }
            if (t.left != null){
                stack.add(t.left);
            }
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/23lalala/p/3506831.html