您的位置:首页 > 其它

LeetCode-144.Binary Tree Preorder Traversal

2016-04-19 15:49 405 查看
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?

/**

 * 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)
{
IList<int> list = new List<int>();
Fun(list, root);
return list;
}

public void Fun(IList<int> list,TreeNode node)
{
if (node!=null)
{
list.Add(node.val);
Fun(list, node.left);
Fun(list, node.right);
}
}
}

非递归解
public IList<int> PreorderTraversal(TreeNode root)
{
IList<int> list = new List<int>();
if (root==null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.Push(root);
TreeNode node;
while (stack.Count>0)
{
node = stack.Pop();
list.Add(node.val);
if (node.right != null)
stack.Push(node.right);
if (node.left != null)
stack.Push(node.left);
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 tree