二叉树的递归遍历
递归三要素
1、确定递归函数的参数和返回值:确定哪些参数是递归的过程中需要处理的,就在递归函数中加上这个参数,并且还要明确每次递归的返回值是什么,进而确定递归函数的返回类型。
2、确定终止条件:写完了递归算法,运行的时候会爆栈,因为没有写终止条件或者是终止条件不对,操作系统使用栈来保存每层递归,递归没有终止,操作系统的内存栈就会溢出。
3、确定单层递归的逻辑:确定每一层递归需要处理的信息。
例如:
- 二叉树的前序遍历
1.确定递归函数的参数和返回值:传入参数为根节点,存储结果的List集合
void preorder(TreeNode root, List<Integer> result)
2.确定终止条件:
if (cur == null) {
return;
}
3.确定单层递归的逻辑
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
144.二叉树的前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
}
二叉树的迭代遍历
- 前序遍历:中 - 左 - 右,入栈顺序:中 - 右 - 左
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty) {
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return result;
}
- 中序遍历:左 - 中 - 右, 入栈顺序:左 - 右
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
- 后序遍历:左 - 右 - 中,入栈顺序:中 - 左 - 右, 出栈顺序:中 - 右 - 左
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
Collections.reverse(result);
return result;
}