首页 > 代码库 > 4. Binary Tree Preorder Traversal

4. 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?

 

 

解法一: Python版本

class Solution:
# @param root, a tree node
# @return a list of integers
  def preorderTraversal(self, root):
    temp = root
    result = []

    if root == None:
      return result

    stack = []
    stack.insert(0, temp)

    while stack:
      temp = stack[0]
      stack.remove(temp)

      if temp.right != None:
        stack.insert(0, temp.right)

      if temp.left != None:
        stack.insert(0, temp.left)

      result.append(temp.val)

    return result

 

 

解法二:JAVA版本

public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
   List<Integer> list = new ArrayList<Integer>();

  if(root == null)
  {
    return list;
  }


  Stack<TreeNode> stack = new Stack<TreeNode>();
  TreeNode temp = root;
  stack.push(temp);

  while(!stack.isEmpty())
  {
    TreeNode t = stack.pop();

    if(t.right!=null)
    {
      stack.push(t.right);
    }

    if(t.left!=null)
    {
      stack.push(t.left);
    }

    list.add(t.val);
  }

  return list;
  }
}

4. Binary Tree Preorder Traversal