diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 69007995..e39709b8 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -695,6 +695,67 @@ impl Solution { } } ``` +### C# +```C# +// 前序遍历 +public IList PreorderTraversal(TreeNode root) +{ + var st = new Stack(); + var res = new List(); + 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 InorderTraversal(TreeNode root) +{ + var st = new Stack(); + var res = new List(); + 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 PostorderTraversal(TreeNode root) +{ + var res = new List(); + var st = new Stack(); + 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; +} +```