题目描述
实现树的前序,中序,后序遍历
解决
前序和后序用的比较少,直接用递归了,中序用的比较多,用两种实现方式
树的节点
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
三种遍历
public class Solution {
public List<Integer> list = new ArrayList<>();
//1.前序遍历
public void preorder(TreeNode root){
if(root != null){
list.add(root.val);
preorder(root.left);
preorder(root.right);
}
}
//2.1中序遍历,递归实现
public void inorder1(TreeNode root){
if(root != null){
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
//2.2迭代和栈实现
public void inorder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.empty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
//3.后序遍历
public void backorder(TreeNode root){
if(root != null){
backorder(root.left);
backorder(root.right);
list.add(root.val);
}
}
}