C#
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;
}
}
先序
public class LeftSolution
{
//先序遍历 根节点-左节点-右节点
public IList<int> InorderTraversal(TreeNode root)
{
IList<int> res = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curNode = new TreeNode();
while (root != null || stack.Count > 0)
{
while (root != null)
{
stack.Push(root); //将每一个根节点推入栈中
res.Add(root.val); //先序遍历的规则, 每一个根节点的值都进入结果res集合
root = root.left; //一直向左遍历
}
curNode = stack.Pop(); //当没有了根节点, 就向上弹出一个站,
root = curNode.right;
}
return res;
}
}
后序
public IList<int> PostorderTraversal(TreeNode root)
{
//后序遍历, 左,右, 根, 可以仿照先序遍历, 求出根, 右, 左, 再reverse
List<int> res = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curNode = new TreeNode();
while (root !=null || stack.Count>0)
{
while (root!=null)
{
stack.Push(root);
res.Add(root.val);
root = root.right;
}
curNode = stack.Pop(); // 向右遍历已经没有了节点, 当前节点返回上一个根节点
root = curNode.left; //回到根节点, 再遍历根节点的左节点
}
res.Reverse();
IList<int> res1 = res;
return res1;
}
中序
public IList<int> InorderTraversal(TreeNode root)
{
IList<int> result = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null)
{
if (root.left != null)//左树不为空,将当前节点压入栈(当前节点以及右树后续处理)
{
stack.Push(root);
root = root.left;
}
else
{
result.Add(root.val);//左树为空,结果集加入当前节点值,处理当前节点右树
root = root.right;
if (root == null && stack.Count > 0)//如果右树为空,处理父节点及右树(如果有)
{
root = stack.Pop();
root.left = null;
}
}
}
return result;
}
//程序2:
IList<int> res = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (stack.Count > 0 || root != null)
{
while(root!=null)
{
stack.Push(root);
root = root.left;
}
root = stack.Pop();
res.Add(root.val);
root = root.right;
}
return res;
java:
先序遍历
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class LeftSolution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode;
while(root!=null || stack.size()>0)
{
while (root!=null)
{
stack.add(root);
res.add(root.val);
root = root.left;
}
curNode = stack.pop();
root = curNode.right;
}
return res;
}
}
中序
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (stack.size() > 0 || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
本文档详细讲解了如何使用C#编程语言实现二叉树的先序(根-左-右)、中序(左-根-右)和后序(左-右-根)遍历算法,并通过实例展示了如何构造和遍历二叉树结构。适合深入理解二叉树数据结构和算法的开发者。
2242

被折叠的 条评论
为什么被折叠?



