深层递归的优化
using System.Collections;
Stack st = new Stack();
//二叉树中序遍历
//递归。。。。
List<int> list = new List<int>();
List<int> inorderTraversal(TreeNode root)
{
if (root == null)
return list;
inorder(root.left);
list.Add(root.val);
inorder(root.right);
return list;
}
void inorder(TreeNode root)
{
if (root == null)
return;
inorder(root.left);
list.Add(root.val);
inorder(root.right);
}
foreach (var item in inorderTraversal(new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null, null), null))))
{
Console.WriteLine(item);
}
//显式栈:
List<int> inorderTraversal1(TreeNode root)
{
List<int> res = new List<int>();
LinkedList<TreeNode> stk = new LinkedList<TreeNode>();
while (root != null || !(stk.Count == 0))
{
while (root != null)
{
stk.AddLast(root);
root = root.left;
}
root = stk.Last();
stk.RemoveLast();
res.Add(root.val);
root = root.right;
}
return res;
}
Console.WriteLine("======================");
foreach (var item in inorderTraversal1(new TreeNode(1, null, new TreeNode(2, new TreeNode(3, null, null), null))))
{
Console.WriteLine(item);
}
//斐波那契
int Fib(int n)
{
if (n == 1 || n == 2) return 1;
else return Fib(n - 1) + Fib(n - 2);
}
Console.WriteLine("===========斐波那契===========");
Console.WriteLine(Fib(16));
//使用缓存
int FibCache(int n)
{
int[] cache = { 0, 1, 1 };
int _fib(int n)
{
if (cache[n] == 1) return cache[n];
cache[n] = _fib(n - 1) + _fib(n - 2);
return cache[n];
}
return _fib(n);
}
Console.WriteLine("===========斐波那契2===========");
Console.WriteLine(Fib(16));
public class TreeNode
{
public int val { get; set; }
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
结果:
1
3
2
======================
1
3
2
===========斐波那契===========
987
===========斐波那契2===========
987
D:\Csharp\ConsoleTest1\ConsoleTest1\bin\Debug\net6.0\ConsoleTest1.exe (进程 2356)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .