标签:
题目:
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 class Solution { 2 public List<Integer> preorderTraversal(TreeNode root) 3 { 4 List<Integer> result = new ArrayList<Integer> (); 5 LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); 6 7 while(root!=null||stack.isEmpty()==false) 8 { 9 if(root!=null) 10 { 11 result.add(root.val); 12 stack.push(root); 13 root=root.left; 14 } 15 else 16 { 17 root=stack.pop(); 18 root=root.right; 19 20 } 21 } 22 23 return result; 24 } 25 }
*Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4709987.html