1.前序遍历
前序遍历的规则:
- 访问根节点
- 前序遍历左子树
- 前序遍历右子树
1.1 递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
solution(root,list);
return list;
}
private static void solution(TreeNode root,List<Integer> list){
if(root == null){
return;
}
//1.访问根节点
list.add(root.val);
//2.前序遍历左子树
solution(root.left,list);
//3.前序遍历右子树
solution(root.right,list);
}
}
1.2 非递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur!=null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
list.add(cur.val);
cur = cur.left;
}
TreeNode rightTree = stack.pop();
cur = rightTree.right;
}
return list;
}
}
2.中序遍历
LeetCode 94 二叉树的中序遍历
中序遍历的规则:
- 中序遍历左子树
- 访问根节点
- 中序遍历右子树
2.1 递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
solution(list,root);
return list;
}
private static void solution(List<Integer> list,TreeNode root){
if(root == null){
return;
}
solution(list,root.left);
list.add(root.val);
solution(list,root.right);
}
}
2.2 非递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.pop();
list.add(node.val);
cur = node.right;
}
return list;
}
}
3.后序遍历
LeetCode 145 二叉树的后序遍历
后序遍历的规则:
- 后序遍历左子树
- 后序遍历右子树
- 遍历根
3.1 递归
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
solution(list,root);
return list;
}
private static void solution(List<Integer> list,TreeNode root){
if(root == null){
return;
}
solution(list,root.left);
solution(list,root.right);
list.add(root.val);
}
}
3.2 非递归
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode flag = null;
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
TreeNode temp = stack.peek();
if(temp.right == null || temp.right == flag){
stack.pop();
list.add(temp.val);
//此处应做标记
flag = temp;
}else{
cur = temp.right;
}
}
return list;
}
}