mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update.统一迭代法,添加C#版
This commit is contained in:
@ -741,6 +741,99 @@ impl Solution{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
### C#
|
||||||
|
```C#
|
||||||
|
// 前序遍历
|
||||||
|
public IList<int> PreorderTraversal(TreeNode root)
|
||||||
|
{
|
||||||
|
var res = new List<int>();
|
||||||
|
var st = new Stack<TreeNode>();
|
||||||
|
if (root == null) return res;
|
||||||
|
st.Push(root);
|
||||||
|
while (st.Count != 0)
|
||||||
|
{
|
||||||
|
var node = st.Peek();
|
||||||
|
if (node == null)
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
node = st.Peek();
|
||||||
|
st.Pop();
|
||||||
|
res.Add(node.val);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
if (node.right != null) st.Push(node.right);
|
||||||
|
if (node.left != null) st.Push(node.left);
|
||||||
|
st.Push(node);
|
||||||
|
st.Push(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```C#
|
||||||
|
// 中序遍历
|
||||||
|
public IList<int> InorderTraversal(TreeNode root)
|
||||||
|
{
|
||||||
|
var res = new List<int>();
|
||||||
|
var st = new Stack<TreeNode>();
|
||||||
|
if (root == null) return res;
|
||||||
|
st.Push(root);
|
||||||
|
while (st.Count != 0)
|
||||||
|
{
|
||||||
|
var node = st.Peek();
|
||||||
|
if (node == null)
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
node = st.Peek();
|
||||||
|
st.Pop();
|
||||||
|
res.Add(node.val);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
if (node.right != null) st.Push(node.right);
|
||||||
|
st.Push(node);
|
||||||
|
st.Push(null);
|
||||||
|
if (node.left != null) st.Push(node.left);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```C#
|
||||||
|
// 后序遍历
|
||||||
|
public IList<int> PostorderTraversal(TreeNode root)
|
||||||
|
{
|
||||||
|
var res = new List<int>();
|
||||||
|
var st = new Stack<TreeNode>();
|
||||||
|
if (root == null) return res;
|
||||||
|
st.Push(root);
|
||||||
|
while (st.Count != 0)
|
||||||
|
{
|
||||||
|
var node = st.Peek();
|
||||||
|
if (node == null)
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
node = st.Peek();
|
||||||
|
st.Pop();
|
||||||
|
res.Add(node.val);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
st.Pop();
|
||||||
|
if (node.left != null) st.Push(node.left);
|
||||||
|
if (node.right != null) st.Push(node.right);
|
||||||
|
st.Push(node);
|
||||||
|
st.Push(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Reverse(0, res.Count);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user