首先手写一遍二叉树的定义:
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;
}
}
前序遍历:中 -> 左 -> 右
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
proceedTreeNode(root,list);
return list;
}
public void proceedTreeNode(TreeNode root,ArrayList list){
if(root == null){
return;
}
list.add(root.val);
proceedTreeNode(root.left,list);
proceedTreeNode(root.right,list);
}
}
中序遍历: 左 -> 中 -> 右
//递归:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
inorderTreeNode(root,list);
return list;
}
public void inorderTreeNode(TreeNode root,ArrayList list){
if(root == null){
return;
}
inorderTreeNode(root.left,list);
list.add(root.val);
inorderTreeNode(root.right,list);
}
}
//迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
//先把要访问的第一个根节点压进去
stack.push(root);
while(!stack.isEmpty()){
//pop出来,为进入list做准备
TreeNode node = stack.pop();
if(node == null){
continue;
}else{
//如果不是空,就list.add
list.add(node.val);
}
//它出去以后,要依次把它的左右节点入栈,注意是先右节点入栈,
再左,因为栈是先进后出的,所以为了左先出栈,先push右
stack.push(node.right);
stack.push(node.left);
}
return list;
}
}
后序遍历:左 -> 右 -> 中
//递归:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
postTreeNode(root,list);
return list;
}
public void postTreeNode(TreeNode root,ArrayList list){
if(root == null){
return;
}
postTreeNode(root.left,list);
postTreeNode(root.right,list);
list.add(root.val);
}
}
//迭代: 前序:中左右 ---中右左 ---翻转:左右中
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if(node == null){
continue;
}
else{
list.add(node.val);
}
stack.push(node.left);
stack.push(node.right);
}
Collections.reverse(list);
return list;
}