递归序
每个节点都会 来到 三次 然后根据在每次来的时候,在哪一次操作,分为三种遍历,都是基于根节点为参考
- 先序, 头 左 右
- 中序, 左 头 右
- 后序, 左 右 头
递归实现
public static class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } } public static void preOrderRecur(Node head) { if (head == null) { return; } // 1 System.out.println(head.value + " "); preOrderRecur(head.left); // 2 preOrderRecur(head.right); // 3 } public static void inOrderRecur(Node head) { if (head == null) { return; } // 1 inOrderRecur(head.left); // 2 System.out.println(head.value + " "); inOrderRecur(head.right); // 3 } public static void postOrderRecur(Node head) { if (head == null) { return; } // 1 postOrderRecur(head.left); // 2 postOrderRecur(head.right); // 3 System.out.println(head.value + " "); }
所有递归都可以改为非递归
先序,非递归
准备一个栈,先把根节点压栈,
开始弹,直到栈为空,弹出来就打印(处理)
如果右节点存在,就先压右节点
如果左节点存在,就后压左节点
public static void preOrderUnRecur(Node head) { if (head == null) { return; } // 先序 非递归实现 // 需要一个栈, Stack<Node> stack = new Stack<>(); // 先把 头节点压进去 stack.push(head); Node cur = null; while (!stack.empty()) { // 弹出 cur = stack.pop(); // 打印处理 System.out.print(cur.value + " "); // 先压右 if (cur.right != null) { stack.push(cur.right); } // 再压左 if (cur.left != null) { stack.push(cur.left); } } }
后序遍历 ,非递归
后序遍历和先序遍历,需要再借助一个栈2
先把头压进栈1,开始弹,弹出来,先不处理,然后压入栈2.
如果有左节点,先压左节点进栈1
如果有右节点,后压右节点进栈1
这样栈1 入栈是头 左 右 , 出栈是 头 右 左
栈2 入栈是 头 右 左, 出栈是 左右头。(左右头就是 后序)
全部完毕之后,栈2依次出栈
public static void postOrderUnRecur(Node head) { if (head == null) { return; } Stack<Node> stack1 = new Stack<>(); Stack<Node> stack2 = new Stack<>(); Node cur = null; stack1.push(head); while (!stack1.empty()) { cur = stack1.pop(); stack2.push(cur); if (cur.left != null) { stack1.push(cur.left); } if (cur.right != null) { stack1.push(cur.right); } } while (!stack2.empty()) { System.out.print(stack2.pop().value + " "); } }
中序遍历,非递归
1:左节点 全部入栈,直到左节点为null,
2:开始弹出,打印处理节点,如果有右节点,重复1,2,
3: 如果没有 右节点,走弹出,
public static void inOrderUnRecur(Node head) { if (head == null) { return; } Stack<Node> stack = new Stack<>(); while (!stack.empty() || head != null) { if (head != null) { stack.push(head); head = head.left; } else { head = stack.pop(); System.out.print(head.value + " "); head = head.right; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统