Skip to content

Commit d87af99

Browse files
author
Li Li
committed
modified solution 94 and 145
1 parent 3e8f746 commit d87af99

File tree

2 files changed

+16
-43
lines changed

2 files changed

+16
-43
lines changed

Algorithms Basics/Chapter 3. Binary Tree/145. Binary Tree Postorder Traversal.cs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,24 +67,25 @@ public IList<int> PostorderTraversal(TreeNode root) {
6767
var stack = new Stack<TreeNode>();
6868
TreeNode lastVisit = null;
6969
while (root != null || stack.Count > 0) {
70-
while (root != null) {
70+
if (root != null) {
7171
stack.Push(root);
7272
root = root.left;
73-
}
74-
root = stack.Peek();
75-
// if root.right == null, then root is leaf, just Add root
76-
// if root.right == lastVisit,
77-
// then both left and right are visited, just Add root
78-
if (root.right == null || root.right == lastVisit) {
79-
res.Add(root.val);
80-
// pop root, mark it as lastvisit, and let root = null,
81-
// so we can keep going to peek stack top for next step
82-
stack.Pop();
83-
lastVisit = root;
84-
root = null;
8573
} else {
86-
// root.right not null, and it's not visited
87-
root = root.right;
74+
root = stack.Peek();
75+
if (root.right != null || root.right != lastVisit) {
76+
// root.right not null, and it's not visited, keep going to right
77+
root = root.right;
78+
} else {
79+
// if root.right == null, then root is leaf, just Add root
80+
// if root.right == lastVisit,
81+
// then both left and right are visited, just Add root
82+
res.Add(root.val);
83+
// pop root, mark it as lastvisit, and let root = null,
84+
// so we can keep going to peek stack top for next step
85+
stack.Pop();
86+
lastVisit = root;
87+
root = null;
88+
}
8889
}
8990
}
9091
return res;

Algorithms Basics/Chapter 3. Binary Tree/94. Binary Tree Inorder Traversal.cs

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,4 @@
11
// recursion
2-
/**
3-
* 利用栈实现循环先序遍历二叉树
4-
* 这种实现类似于图的深度优先遍历(DFS)
5-
* 维护一个栈,将根节点入栈,然后只要栈不为空,出栈并访问,接着依次将访问节点的右节点、左节点入栈。
6-
* 这种方式应该是对先序遍历的一种特殊实现(看上去简单明了),但是不具备很好的扩展性,在中序和后序方式中不适用
7-
*/
82
public class Solution {
93
public IList<int> InorderTraversal(TreeNode root) {
104
var res = new List<int>();
@@ -20,28 +14,6 @@ public IList<int> InorderTraversal(TreeNode root) {
2014
}
2115
}
2216

23-
/*
24-
* 利用栈模拟递归过程实现循环先序遍历二叉树
25-
* 这种方式具备扩展性,它模拟递归的过程,将左子树点不断的压入栈,直到null,然后处理栈顶节点的右子树
26-
*/
27-
public class Solution {
28-
public IList<int> PreorderTraversal(TreeNode root) {
29-
var res = new List<int>();
30-
if (root == null) return res;
31-
Stack<TreeNode> stack = new Stack<TreeNode>();
32-
while (root != null || stack.Count > 0) {
33-
while (root != null) {
34-
res.Add(root.val);
35-
stack.Push(root);
36-
root = root.left;
37-
}
38-
root = stack.Pop();
39-
root = root.right;
40-
}
41-
return res;
42-
}
43-
}
44-
4517
/**
4618
*
4719
* @param root 树根节点

0 commit comments

Comments
 (0)