一、 题目描述
先了解二叉树三种遍历的规则:
- 前序遍历:根——左——右
- 中序遍历:左——根——右
- 后序遍历:左——右——根
二、解题思路
用递归求解,来具体谈谈递归,写递归注意三要素:
-
确定递归函数的参数和返回值:
确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。 -
确定终止条件:
写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。 -
确定单层递归的逻辑:
确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。
三、代码编写步骤
第一步:先声明一个list来存储每次遍历的结果。
第二步:编写递归函数,按照上面的递归三要素来带入到题中。
第三步:主函数调用编写的递归实现。
四、代码演示
4.1 前序遍历代码演示
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
//list集合用来存储答案
List<Integer> res = new ArrayList<Integer>();
//调用方法并传参数
preorderMethod(root,res);
return res;
}
//递归函数,根节点和每次遍历的结果是需要处理的,作为参数传递
public void preorderMethod(TreeNode root, List<Integer> res){
//确定递归终止条件
if(root == null){
return;
}
//确定单层递归的逻辑,前序遍历是根——左——右,所以先遍历根节点
res.add(root.val);
preorderMethod(root.left, res);
preorderMethod(root.right, res);
}
}
4.2 中序遍历代码演示
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
//List是一个接口,<>表示List里面放的对象是什么类型,ArrayList是List接口的一个实现类
List<Integer> res = new ArrayList<Integer>();
//调用inorder方法,传两个参数root和res
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res){
if (root==null){
return;
}
//递归调用(root.left)来遍历root节点的左子树,然后将root节点的值加入到res中
inorder(root.left,res);
//最后的答案res中添加元素
res.add(root.val);
//递归调用inorder(root.right)来遍历root节点的右子树即可,递归终止的条件为碰到空节点。
inorder(root.right, res);
}
}
4.3 后序遍历代码演示
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
postOrder(root, res);
return res;
}
public void postOrder(TreeNode root, List<Integer> res){
if(root == null){
return;
}
postOrder(root.left, res);
postOrder(root.right, res);
//根节点最后打印
res.add(root.val);
}
}
总结
这里将二叉树三种遍历方式的解题放在了一起,分析了递归实现,算是自己的一个总结,不足之处望指教。

被折叠的 条评论
为什么被折叠?



