Update.二叉树迭代遍历,C#版

This commit is contained in:
eeee0717
2023-11-12 09:15:59 +08:00
parent 8945fd9809
commit 5d9d37f01d

View File

@ -695,6 +695,67 @@ impl Solution {
} }
} }
``` ```
### C#
```C#
// 前序遍历
public IList<int> PreorderTraversal(TreeNode root)
{
var st = new Stack<TreeNode>();
var res = new List<int>();
if (root == null) return res;
st.Push(root);
while (st.Count != 0)
{
var node = st.Pop();
res.Add(node.val);
if (node.right != null)
st.Push(node.right);
if (node.left != null)
st.Push(node.left);
}
return res;
}
// 中序遍历
public IList<int> InorderTraversal(TreeNode root)
{
var st = new Stack<TreeNode>();
var res = new List<int>();
var cur = root;
while (st.Count != 0 || cur != null)
{
if (cur != null)
{
st.Push(cur);
cur = cur.left;
}
else
{
cur = st.Pop();
res.Add(cur.val);
cur = cur.right;
}
}
return res;
}
// 后序遍历
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 cur = st.Pop();
res.Add(cur.val);
if (cur.left != null) st.Push(cur.left);
if (cur.right != null) st.Push(cur.right);
}
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">