题解及更详细解答来自于:代码随想录 (programmercarl.com)
前言: 递归三要素

题目链接: 144. 二叉树的前序遍历 - 力扣(LeetCode)
1.确定参数和返回值,我们只需传入一个树节点和一个result数组即可
public void preOrder(TreeNode cur,Listresult) 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,Listresult) 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,Listresult) 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);
- }
- }