Skip to content

Commit 0ba73a4

Browse files
committed
inorder tree using stack
1 parent 7dab94a commit 0ba73a4

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Tree/Tree.TreeLib/InorderStack.cs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/* ==============================================================================
2+
* 功能描述:InorderStack
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+
//Definition for a binary tree node.
29+
public class TreeNode
30+
{
31+
public int val;
32+
public TreeNode left;
33+
public TreeNode right;
34+
public TreeNode(int x) { val = x; }
35+
}
36+
37+
/// <summary>
38+
/// InorderStack
39+
/// </summary>
40+
public class InorderStack
41+
{
42+
public IList<int> InorderTraversal(TreeNode root)
43+
{
44+
IList<int> rtn = new List<int>();
45+
Stack<TreeNode> s = new Stack<TreeNode>();
46+
if (root == null) return rtn;
47+
s.Push(root);
48+
while (s.Count>0)
49+
{
50+
var tmp = s.Peek(); //tmp可能为null ,因为curNode.right可能为null
51+
while (tmp != null) //tmp=null退出循环
52+
{
53+
s.Push(tmp.left);
54+
tmp = tmp.left;
55+
}
56+
s.Pop();
57+
if (s.Count == 0)
58+
return rtn;
59+
rtn.Add(s.Peek().val); //访问节点
60+
TreeNode curNode = s.Pop();
61+
s.Push(curNode.right);
62+
}
63+
return rtn;
64+
}
65+
}
66+
67+
68+
}

0 commit comments

Comments
 (0)