Skip to content

Commit d2f2840

Browse files
committed
preorder tree using stack
1 parent 0ba73a4 commit d2f2840

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Tree/Tree.TreeLib/PreOrderStack.cs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/* ==============================================================================
2+
* 功能描述:PreorderStack
3+
* 创 建 者:gz
4+
* 创建日期:2017/5/12 15:06:49
5+
* ==============================================================================*/
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
using System.Windows.Forms;
11+
using System.Windows.Forms.VisualStyles;
12+
13+
//Given a binary tree, return the inorder traversal of its nodes' values.
14+
15+
//For example:
16+
//Given binary tree [1,null,2,3],
17+
// 1
18+
// \
19+
// 2
20+
// /
21+
// 3
22+
//return [1,3,2].
23+
24+
//Note: Recursive solution is trivial, could you do it iteratively?
25+
namespace InorderTreeStackSln
26+
{
27+
28+
29+
/// <summary>
30+
/// InorderStack
31+
/// </summary>
32+
public class PreorderStack
33+
{
34+
public IList<int> PreorderTraversal(TreeNode root)
35+
{
36+
IList<int> rtn = new List<int>();
37+
if (root == null) return rtn;
38+
39+
Stack<TreeNode> s = new Stack<TreeNode>();
40+
s.Push(root);
41+
TreeNode tmp = root;
42+
while (s.Count > 0)
43+
{
44+
if (tmp == null)
45+
tmp = s.Peek();
46+
rtn.Add(s.Peek().val);
47+
s.Pop();
48+
if(tmp.right!=null)
49+
s.Push(tmp.right);
50+
if (tmp.left != null)
51+
s.Push(tmp.left);
52+
tmp = tmp.left;
53+
}
54+
return rtn;
55+
}
56+
}
57+
58+
59+
}

0 commit comments

Comments
 (0)