卖萌的弱渣

I am stupid, I am hungry.

Binary Tree Preorder Traversal

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

Example:

Given binary tree {1,#,2,3},

1
2
3
4
5
   1
    \
     2
    /
   3

return [1,2,3].

Note:

Recursive solution is trivial, could you do it iteratively?

Solution

  • Java: Iterative
(Binary-Tree-Preorder-Traversal.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 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> ret = new LinkedList<Integer>();
        if(root==null)
            return ret;
        Stack<TreeNode> rights = new Stack<TreeNode>();

        while(root!=null){
            ret.add(root.val);
            if(root.right!=null)
                rights.push(root.right);

            root = root.left;
            if (root==null && !rights.isEmpty())
                root = rights.pop();
        }
        return ret;
    }
}
  • Python: recursive
(Binary-Tree-Preorder-Traversal.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """

        ret = []
        self.searchTree(root,ret)
        return ret

    def searchTree(self, root, ret):
        if root == None:
            return
        ret.append(root.val)
        if root.left != None:
            self.searchTree(root.left,ret)
        if root.right!=None:
            self.searchTree(root.right,ret)
        return