import java.util.*;
public class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
// write your code here
if (root == null){
return null;
}
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()){
if (root != null){
list.add(root.val);
stack.push(root);
root = root.left;
}else {
root = stack.pop();
root = root.right;
}
}
return list;
}
List<Integer> inorederList = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
// write your code here
if (root == null){
return null;
}
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()){
if (root != null){
stack.push(root);
root = root.left;
}else {
root = stack.pop();
inorederList.add(root.val);
root = root.right;
}
}
return inorederList;
}
List<Integer> backorder = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
// write your code here
TreeNode pre = null;
if (root == null){
return null;
}
Stack<TreeNode> stack = new Stack<>();
while (root != null){
stack.push(root);
root = root.left;
}
while (!stack.isEmpty()){
root = stack.pop();
//一个根节点被访问的前提是无右子树或者右子树已经被访问过
if (root.right != null && root.right != pre){
stack.push(root);
root = root.right;
while (root != null){
stack.push(root);
root = root.left;
}
}else {
backorder.add(root.val);
pre = root;
}
}
return backorder;
}
public List<List<Integer>> levelOrder(TreeNode root) {
// write your code here
if (root ==null){
return null;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
List<List<Integer>> lines = new ArrayList<>();
List<Integer> line1 = new ArrayList<>();
line1.add(root.val);
lines.add(line1);
while (!queue.isEmpty()){
List<Integer> line = new ArrayList<>();
for (int i = 0; i< lines.get(lines.size()-1).size();i++){
TreeNode node = queue.poll();
if (node.left!= null){
queue.add(node.left);
line.add(node.left.val);
}
if (node.right != null){
queue.add(node.right);
line.add(node.right.val);
}
}
if (line.size()!= 0){
lines.add(line);
}
}
Collections.reverse(lines);
return lines;
}
}
二叉树遍历非递归实现
最新推荐文章于 2025-04-01 15:42:39 发布