递归实现:
1 1 /** 2 2 * Definition for a binary tree node. 3 3 * public class TreeNode { 4 4 * public int val; 5 5 * public TreeNode left; 6 6 * public TreeNode right; 7 7 * public TreeNode(int x) { val = x; } 8 8 * } 9 9 */ 10 10 public class Solution { 11 11 public IList<int> PreorderTraversal(TreeNode root) { 12 12 List<int> result=new List<int>(); 13 13 if (root==null) 14 14 return result; 15 15 result.Add(root.val); 16 16 if(root.left!=null) 17 17 result.AddRange(PreorderTraversal(root.left)); 18 18 if(root.right!=null) 19 19 result.AddRange(PreorderTraversal(root.right)); 20 20 return result; 21 21 } 22 22 } 23 24
迭代实现:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public IList<int> PreorderTraversal(TreeNode root) { List<int> result=new List<int>();
Stack stack=new Stack();
TreeNode currentNode=root;
while(currentNode!=null||stack.Count!=0)
{
stack.Push(currentNode);
result.Add(currentNode.val);
currentNode=currentNode.left;
while(currentNode==null&&stack.Count!=0)
{
TreeNode parent=stack.Pop() as TreeNode;
currentNode=parent.right;
}
}
return result; } }