·  阅读 231

# 二叉树的遍历

`tree`的结构

### 结构

``````    public class TreeNode
{
public int val;
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;
}
}

### 前序遍历

• 递归

``````public void PreorderTraversal(TreeNode root)
{
if(root==null) return;
Console.WriteLine(root.val);//<--
PreorderTraversal(root.left);
PreorderTraversal(root.right);
}
复制代码``````
• ``````public void InorderTraversal(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();

while (root.Any())
{
TreeNode node=stack.Peek();
if (node!=null)//入栈时反着来的
{
stack.Pop();
if(node.right!=null) stack.Push(node.right);
if(node.left!=null) stack.Push(node.left);
stack.Push(node);
stack.push(null);
}else{
stack.Pop();
node=stack.Peek();
stack.Pop();
Console.WriteLine(node.val);//<--
}
}
}
复制代码``````

### 中序遍历

• 递归

``````public void InorderTraversal(TreeNode root)
{
if(root==null) return;
PreorderTraversal(root.left);
Console.WriteLine(root.val);//<--
PreorderTraversal(root.right);
}
复制代码``````
• ``````public void InorderTraversal(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();

while (stack.Any())
{
TreeNode node=stack.Peek();
if (node!=null)
{
stack.Pop();
if(node.right!=null) stack.Push(node.right);
stack.Push(node);
stack.push(null);
if(node.left!=null) stack.Push(node.left);
}else{
stack.Pop();
node=stack.Peek();
stack.Pop();
Console.WriteLine(node.val);//<--
}
}
}
复制代码``````

### 后序遍历

• 递归

``````public void PostorderTraversal(TreeNode root)
{
if(root==null) return;
PreorderTraversal(root.left);
PreorderTraversal(root.right);
Console.WriteLine(root.val);//<--
}
复制代码``````
• ``````public void InorderTraversal(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();

while (stack.Any())
{
TreeNode node=stack.Peek();
if (node!=null)//入栈时反着来的
{
stack.Pop();
stack.Push(node);
stack.push(null);

if(node.right!=null) stack.Push(node.right);
if(node.left!=null) stack.Push(node.left);
}else{
stack.Pop();
node=stack.Peek();
stack.Pop();
Console.WriteLine(node.val);
}
}
}
复制代码``````

### 层序遍历

• 利用队列(BFS)

``````public void InorderTraversal(TreeNode root)
{
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(tree);
int depth = 1;
while (queue.Count>0)
{
var len = queue.Count;
for (int i = 0; i < len; i++)
{
var cur = queue.Dequeue();
Console.WriteLine("节点 {0} 在第 {1} 层",cur.val, depth);
if (cur.left != null)
queue.Enqueue(cur.left);
if (cur.right != null)
queue.Enqueue(cur.right);
}
depth++;
}
}
复制代码``````