LeetCode:二叉树小结
说明
此文章记录LeetCode中前序,中序,后序迭代遍历以及层次遍历,说明并不是很多,更多的可能是方便自己回顾,如果对您有所帮助,更是欣喜。
前中后都可以进行递归编写,因此迭代遍历肯定需要借助栈来完成,因为递归的本质就是栈。层次遍历有所不同,需要队列来完成,它的实质是广度优先遍历。
递归遍历
比较简单,以前序为例,其他的仅仅改变helper中res.add的位置即可
//普遍写法(通过void类型来写)
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
helper(root);
return res;
}
public void helper(TreeNode root) {
if (root == null) return;
res.add(root.val);
helper(root.left);
helper(root.right);
}
}
如果我们想写出非void类型来写也是可以的。如下:
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
return helper(root);
}
public List<Integer> helper(TreeNode root) {
//这里的return 绝大部分是没有用的,只有当初始二叉树的根节点为空,这里需要返回应该空列表,
//其他时候这个函数最终都会在最后一排的return离开,所以这里只要处理好初始二叉树为空的情况
//就可以,比如return res;return new LinkedList<Interger>;
if (root == null) return res;
res.add(root.val);
helper(root.left);
helper(root.right);
return res;
}
}
或者下面这样:
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if (root!=null) helper(root);
return res;
}
public List<Integer> helper(TreeNode root){
res.add(root.val);
if (root.left!=null) helper(root.left);
if (root.right!=null) helper(root.right);
return res;
}
//如果要改变成普遍写法
public List<Integer> helper(TreeNode root){
if (root == null) return res;
//这一块这个return是没什么用的,因为我们可以看到递归调用helper(root)是没有值接受的,这里我们还是把它当成了void来用的,但是必须得返回一个Lint<Integer>类型的数据,因为我们函数的返回值是这个类型的
res.add(root.val);
helper(root.left);
helper(root.right);
return res;
}
}
咱们再来试试中序递归遍历,同时试着修改一下函数的类型:
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root!=null) midOrder(root);
return res;
}
public void midOrder(TreeNode root){
if (root.left != null) midOrder(root.left);
res.add(root.val);
if (root.right != null) midOrder(root.right);
}
}
还是推荐最上面的第一种或第二种写法,因为这是最基础的先序递归遍历,当我们需要通过这个模型做题目时,通常都会复杂一点的,我们需要在普遍的基础上改装更方便,递归更容易思考,不妨试着写一下void类型的中序遍历以及后序遍历。
前序迭代遍历——leetcode:144
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
List<Integer> res = new ArrayList<>();
if (root==null) return res;
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.add(node.val);
if (node.right!=null) stack.push(node.right);
if (node.left!=null) stack.push(node.left);
}
return res;
}
}
理解图:
中序迭代遍历——leetcode:94
这里推荐第一种吧,和前序迭代遍历的格式比较相似,思路比较好表达一些,注意点就是其中要将left=null,不然可能会出问题。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root == null) return res;
stack.push(root);
while (!stack.isEmpty()){
while(root.left != null){
stack.push(root.left);
root = root.left;
}
root = stack.pop();
root.left = null;
res.add(root.val);
if (root.right !=null){
stack.push(root.right);
root = root.right;
}
}
return res;
}
}
第二种写法的思路其实和第一种是一个意思,但是由于写法差异比较大,不好记忆,前中后记一种模型就可以了。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
List<Integer> src = new ArrayList<>();
while (!stack.isEmpty()||root!=null){
if (root != null){
stack.push(root);
root = root.left;
}else{
root = stack.pop();
src.add(root.val);
root = root.right;
}
}
return src;
}
}
理解图:
后序序迭代遍历——leetcode:145
这里需要稍稍说明一下,这里的后序遍历是由前序遍历变来的:
后序遍历中遍历的顺序是左右中,而前序的顺序是中左右,如果我们改变一下左右结点进栈的顺序,就会变成中右左(这个没有实际的意义),接着我们只要倒序便可以完成左右中,及后序遍历,其中倒序可以通过LinkedList中addFirst来完成,当然也可以通过Collections.reverse()来完成,我这里用的是addFirst;
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
//List中不可以使用addFirst,所以只能用LinkedList声明
LinkedList<Integer> src = new LinkedList<>();
if (root==null) return src;
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
src.addFirst(node.val);
if (node.left!=null) stack.push(node.left);
if (node.right!=null) stack.push(node.right);
}
return src;
}
}
层次遍历——leetcode:102
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if (root==null) return res;
queue.add(root);
while(!queue.isEmpty()){
LinkedList<Integer> tem = new LinkedList<>();
for (int i=queue.size();i>0;i--){
TreeNode node = queue.poll();
tem.add(node.val);
if (node.left!=null) queue.add(node.left);
if (node.right!=null) queue.add(node.right);
}
res.add(tem);
}
return res;
}
}
剑指 Offer 68 - II. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中
思路一:递归
先从根节点思考:
我们可以知道这个根节点的左边和右边,在这个基础上找两个点,有几种情况?
- 左右两边都没有这两个点
- 左边没有,全部在根节点的左边
- 右边没有,全部在根节点的右边
- 在根节点的左右两边(一边一个)或者这个根节点就是其中一个点(两个之中的一个),这时这个点就是最近公共祖先
递归的核心在于假设子问题已经解决,我们在已经解决的基础上思考即可。
所以我们可以通过递归当作这个节点的左右节点,问题转换成如下:
已知根节点,根节点左边情况,根节点右边情况,还有2个目标节点:
从解决问题的角度去看:
已知:root;left;right;
首先考虑递归的终结条件:当root==null,没有left和right,就是说这一块没有目标点,返回null回去说明
其次,当root==p||root==q时,说明我们找到了目标点,并返回回去这个目标点,说明了这一边有目标节点
if (left==null&&right==null) return null;//左边没有右边没有,就是没有
if (left==null) return right;//左边没有右边有,就去右边看看
if (right==null) return left;//左边有右边没有,就去左边看看
return root;//左边有右边有,这个点就是目标
递归式:
可以理解为判断左边和右边是否有目标值(终止条件也是为了这个递归式服务)
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
由此我们必须得到这个函数的返回值必须为我们需要寻找的值,及p或q,因为只有是p或者q,我们上面设置的left和right才有意义。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//终止条件
if (root == null || root == p || root==q) return root;
//递归找到p或q并记录
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
//回溯的判断,回溯是从最下面往上进行的,所以如果有left和right都不为空,就是我们最终想要去找的答案
//上面的回溯是我最初的想法,实际该题应该是一个后续遍历,下面就是判断从下往上的过程中是否有符合条件的点。有待思考这一块。
if (left==null&&right==null) return null;
if (left==null) return right;
if (right==null) return left;
return root;
}
}
再补上一个更简洁的答案:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == root || q == root) {
return root;
}
TreeNode l = lowestCommonAncestor(root.left, p, q);
TreeNode r = lowestCommonAncestor(root.right, p, q);
return l == null ? r : (r == null ? l : root);
}
}
拓展:递归分析
其实刚开始接触递归的时候,我们很容易绕进循环的思维里出不来,最好的做法是平时偶尔思考几次递归的过程,应用的时候就当子问题已经解决来处理,平时的思考是为了加深对递归的理解,这里我就来带大家进行平时的思考,分析一下这里的递归到底是怎么进行的。
先给上我记录节点的代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root==q) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
//打印记录过程
System.out.print("root: "+root.val+" ");
if (left!=null) System.out.println("left: "+left.val+" ");
else System.out.println("left:null ");
TreeNode right = lowestCommonAncestor(root.right,p,q);
//打印记录过程
System.out.print("root: "+root.val+" ");
if (left!=null) System.out.print("left: "+left.val+" ");
else System.out.print("left:null ");
if (right!=null) System.out.println("right: "+right.val);
else System.out.println("right:null");
if (left==null&&right==null) return null;
if (left==null) return right;
if (right==null) return left;
return root;
}
}
首先我们来思考一下两个节点在两边的时候,就比如上面树的2和8
这里的递归过程建议对照着上面的输出思考。
然后我们再来思考一下两个节点在一边的时候,就比如上面树的5和4:
思路二:记录父节点
这个方法我觉得最好的地方在于记录了父节点,这个思想可以用在很多地方,可以实现二叉树一个路径的逆方向输出。
public void preOrder(TreeNode root){
if (root.left!=null){
hashmap.put(root.left.val,root);
preOrder(root.left);
}
if (root.right!=null){
hashmap.put(root.right.val,root);
preOrder(root.right);
}
}
下面给上该题具体的解决方案:
class Solution {
Map<Integer,TreeNode> hashmap = new HashMap<>();
Set<TreeNode> visited = new HashSet<>();
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
preOrder(root);
while (p!=null){
System.out.println(p.val);
visited.add(p);
p = hashmap.get(p.val);
}
while(q!=null){
if (visited.contains(q)){
return q;
}else{
q = hashmap.get(q.val);
}
}
return null;
}
public void preOrder(TreeNode root){
if (root.left!=null){
hashmap.put(root.left.val,root);
preOrder(root.left);
}
if (root.right!=null){
hashmap.put(root.right.val,root);
preOrder(root.right);
}
}
}