题解及更详细解答来自于:代码随想录 (programmercarl.com)
前言: 递归三要素
确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。
确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
确定单层递归的逻辑: 确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。
题目链接: 144. 二叉树的前序遍历 - 力扣(LeetCode)
1.确定参数和返回值,我们只需传入一个树节点和一个result数组即可
public void preOrder(TreeNode cur,List
result) 2.确认终止条件,当我们遍历的节点为空的时候,递归停止
if(cur == null) { return ; }
3.确认单层递归的逻辑:中左右的顺序递归
result.add(cur.val); preOrder(cur.left,result); preOrder(cur.right,result);
/**
* Definition for a binary tree node.
* public 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 preorderTraversal(TreeNode root) {
List list = new ArrayList<>();
preOrder(root,list);
return list;
}
public void preOrder(TreeNode cur,List result)
{
if(cur == null)
{
return ;
}
result.add(cur.val);
preOrder(cur.left,result);
preOrder(cur.right,result);
}
}
题目链接: 94. 二叉树的中序遍历 - 力扣(LeetCode)
1.确定参数和返回值,我们只需传入一个树节点和一个result数组即可
public void inOrder(TreeNode cur,List
result) 2.确认终止条件,当我们遍历的节点为空的时候,递归停止
if(cur == null) { return ; }
3.确认单层递归的逻辑:左中右的顺序递归
inOrder(cur.left,result); result.add(cur.val); inOrder(cur.right,result);
/**
* Definition for a binary tree node.
* public 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 inorderTraversal(TreeNode root) {
List result = new ArrayList<>();
inOrder(root,result);
return result;
}
public void inOrder(TreeNode cur,List result)
{
if(cur == null)
{
return ;
}
inOrder(cur.left,result);
result.add(cur.val);
inOrder(cur.right,result);
}
}
题目链接: 145. 二叉树的后序遍历 - 力扣(LeetCode)
1.确定参数和返回值,我们只需传入一个树节点和一个result数组即可
public void postOrder(TreeNode cur,List
result) 2.确认终止条件,当我们遍历的节点为空的时候,递归停止
if(cur == null) { return ; }
3.确认单层递归的逻辑:左中右的顺序递归
postOrder(cur.left,result); postOrder(cur.right,result); result.add(cur.val);
/**
* Definition for a binary tree node.
* public 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 postorderTraversal(TreeNode root) {
List result = new ArrayList<>();
postOrder(root,result);
return result;
}
public void postOrder(TreeNode cur,List result)
{
if(cur == null)
{
return;
}
postOrder(cur.left,result);
postOrder(cur.right,result);
result.add(cur.val);
}
}