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
return
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;
}
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;
}
相关文章推荐
- 命令行快速技巧:如何定位一个文件
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析