import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution {
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null){
stack.push(root);
}
while(!stack.isEmpty()){
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();
result.add(node.val);
}
}
return result;
}
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null){
stack.push(root);
}
while(!stack.isEmpty()){
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();
result.add(node.val);
}
}
return result;
}
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null){
stack.push(root);
}
while(!stack.isEmpty()){
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();
result.add(node.val);
}
}
return result;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
代码随想录算法训练营第十四天 迭代法遍历
最新推荐文章于 2024-08-19 11:12:00 发布