144. 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     private void frontParserTree(TreeNode root,List<Integer> result)
 2     {
 3         if (root == null) return;
 4         result.add(root.val);
 5         frontParserTree(root.left,result);
 6         frontParserTree(root.right,result);
 7     }    
 8     public List<Integer> preorderTraversal(TreeNode root) {
 9           List<Integer> result = new ArrayList<>();
10         frontParserTree(root,result);
11         return result;      
12     }

 

方法二:

 1     public List<Integer> preorderTraversal(TreeNode root) {
 2         List<Integer> list = new LinkedList<Integer>();
 3         Stack<TreeNode> rights = new Stack<TreeNode>();
 4         while(root != null) {
 5             list.add(root.val);
 6             if (root.right != null)  rights.push(root.right);
 7             root = root.left;
 8             if (root == null && !rights.isEmpty()) root = rights.pop();
 9         }
10         return list;
11     }

 

posted @ 2017-10-23 08:07  daniel456  阅读(125)  评论(0编辑  收藏  举报