一、递归实现二叉树遍历
1)前序遍历:root ,left,right。
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
inorder(root);
return list;
}
public void inorder(TreeNode root){
if(root != null){
list.add(root.val);
inorder(root.left);//递归
inorder(root.right);
}
}
}
2)中序遍历:left,root,right
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inorder(root);
return list;
}
public void inorder(TreeNode root){
if(root != null){
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
}
3)后序遍历:left,right,root
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return list;
inorder(root);
return list;
}
public void inorder(TreeNode root){
if(root != null){
inorder(root.left);
inorder(root.right);
list.add(root.val);
}
}
二、迭代实现二叉树遍历
1)前序遍历
/*
使用栈作为辅助
1,考虑出栈的是什么,前序遍历,出栈顺序为root ,left,right
2,root先入栈,判断栈是否为空,然后根出栈,加入结果list中,判断当前节点是否还有左右孩子
*/
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root ==null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);//根入栈
while(!stack.isEmpty()){
TreeNode outNode = stack.pop();//根出栈
list.add(outNode.val);
if(outNode.right != null){//先加右孩子,因为栈是先进后出
stack.push(outNode.right);
}
if(outNode.left != null){
stack.push(outNode.left);
}
}
return list;
}
}
2)中序遍历
/*
1,定义一个list集合
2,使用栈作为辅助
3,中序遍历,左孩子全部入栈,然后root,然后右孩子
*/
class Solution {
private List<Integer> result = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
//TreeNode current = root;
while(!stack.isEmpty() || root != null){
if(root != null){//当前节点不为空,把当前节点的全部左孩子放入栈中
stack.push(root);
root = root.left;
}else{
root = stack.pop();//左孩子出栈
result.add(root.val);
root = root.right;
}
}
return result;
}
}
3)二叉树后序遍历
/*
后序遍历,左,右 root。
向list头部添加,出栈顺序为root ,right,left
*/
class Solution {
private List<Integer> result = new ArrayList<Integer>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
//root入栈
stack.push(root);
while(!stack.isEmpty()){
TreeNode outNode = stack.pop();//根节点出栈
if(outNode.left != null){//出栈顺序为 root ,right,left,所以先left入栈
stack.push(outNode.left);
}
if(outNode.right!= null){
stack.push(outNode.right);
}
result.add(0,outNode.val);//向list头部添加,后面的数会自动向后加1
}
return result;
}
}