144. Binary Tree Preorder Traversal

题目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?

1,递归
public List preorderTraversal(TreeNode root) {
        List result = new ArrayList();
        dfs(root, result);
        return result;
    }
    
    private void dfs(TreeNode root, List result){
        if(root == null){
            return;
        }
        result.add(root.val);
        dfs(root.left,result);
        dfs(root.right,result);
    }
2,非递归
public List preorderTraversal(TreeNode root) {
        List result = new ArrayList();
        Stack stack = new Stack();
        if(root != null){
            stack.push(root);
        }
        TreeNode tempNode = null;
        while(!stack.empty()){
            tempNode = stack.pop();
            result.add(tempNode.val);
            if(tempNode.right != null){
                stack.push(tempNode.right);
            }
            
            if(tempNode.left != null){
                stack.push(tempNode.left);
            }
        }
        return result;
    }

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