前序遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<Integer>();
Stack<TreeNode>stack=new Stack<TreeNode>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
list.add(root.val);
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
root=root.right;
}
}
return list;
}
}
中序迭代遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
Stack<TreeNode>stack=new Stack<TreeNode>();
while(root!=null||!stack.isEmpty()) {
while(root!=null) {//先将左结点入栈
stack.push(root);
root=root.left;
}
if(!stack.empty()) {
root=stack.pop();
list.add(root.val);
root=root.right;//如果当前结点有右结点遍历它的右结点
}
}
return list;
}
}
后序迭代遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<Integer>();
Stack<TreeNode>stack=new Stack<TreeNode>();
TreeNode q=null;
while(root!=null||!stack.isEmpty()) {
while(root!=null) {
stack.push(root);
root=root.left;
}
if(!stack.empty()) {
root=stack.peek();//取得结点但不让它出栈
if((root.right==null)||(root.right==q)){//判断该节点的右结点是否访问过
stack.pop();
list.add(root.val);
q=root;
root=null;
}
else{
root=root.right;
}
}
}
return list;
}
}
继续阅读与本文标签相同的文章
-
选择按钮搭配VBA实现数据小型自动化
2026-05-18栏目: 教程
-
Python高级进阶#011 pyqt5按钮QPushButton应用
2026-05-18栏目: 教程
-
Apache Solr Velocity模版注入远程命令执行漏洞复线
2026-05-18栏目: 教程
-
从订货会的功能变迁看出版业的沧海桑田
2026-05-18栏目: 教程
-
ASP.NET Core on K8S深入学习(9)Secret & Configmap
2026-05-18栏目: 教程
