文章目录
Day 18 第六章 二叉树 part05
- 今日内容
- ● 513.找树左下角的值
- ● 112. 路径总和 113.路径总和ii
- ● 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树
513.找树左下角的值
- 本地递归偏难,反而迭代简单属于模板题, 两种方法掌握一下
- 题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
- 视频讲解:https://www.bilibili.com/video/BV1424y1Z7pn
- 文章讲解:https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html
自己的思路 - 层序遍历(✅通过但时间太长)
用层序遍历,把每层第一个数加入一个新栈,返回栈顶即可
public static int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
//队列里元素的个数就是每一层元素的个数
int size = queue.size();
//System.out.println("peek:"+queue.peek().toString());
stack.push(queue.peek());
//不能直接把queue.size()写进for循环,因为循环的时候queue.size()会变
for(int i = 0; i < size; i++){
TreeNode poll = queue.poll();
System.out.println(poll.val+" ");
if(poll.left != null) queue.offer(poll.left);
if(poll.right != null) queue.offer(poll.right);
}
}
return stack.peek().val;
}
随想录代码 - 层序遍历
优化思路:只定义一个int类型的res,for循环的第一个数就赋给res即可
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
if (i == 0) {
res = poll.val;
}
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
}
}
return res;
}
随想录代码 - 递归
思路:找深度最大的叶子节点最左侧的节点
private int maxDeep = -1;//二叉树的最大深度
private int res = 0;//结果
public int findBottomLeftValue(TreeNode root) {
res = root.val;
findLeftValue(root,0);
return res;
}
private void findLeftValue (TreeNode root,int deep) {
//节点为空
if (root == null) return;
//当递归到子节点,结束递归
if (root.left == null && root.right == null) {
//如果比之前记录的深度要深
if (deep > maxDeep) {
//更新结果
res = root.val;
//更新最大深度
maxDeep = deep;
}
}
if (root.left != null) findLeftValue(root.left,deep + 1);
if (root.right != null) findLeftValue(root.right,deep + 1);
}
if (root.left != null) findLeftValue(root.left,deep + 1);
//相当于
if (root.left != null) {
deep ++;
findLeftValue(root.left,deep);
deep --; //回溯的过程
}
112.路径总和+113.路径总和ii
- 本题 又一次设计要回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解
- 路径总和,和 113. 路径总和ii 一起做了。 优先掌握递归法。
- 题目链接:
- 视频讲解:https://www.bilibili.com/video/BV19t4y1L7CR
- 文章讲解:https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html
112.路径总和
思路
同113,只是返回值变为true和false
代码
public static boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
targetSum -= root.val;
// 叶子结点
if (root.left == null && root.right == null) {
return targetSum == 0;
}
if (root.left != null) {
boolean left = hasPathSum(root.left, targetSum);
if (left) { // 已经找到
return true;
}
}
if (root.right != null) {
boolean right = hasPathSum(root.right, targetSum);
if (right) { // 已经找到
return true;
}
}
return false;
}
113.路径总和ii
思路
走到哪个节点就用targetSum-root.val
,并且把root
加入path
走到叶子节点通过判断targetSum
是否为0来确定是否是一条正确的路径
然后进行递归
递归之后进行回溯!重新进行path
代码&重点
- 必须要回溯path
- 当把path赋值给res时,得先用path新建一个数组
new ArrayList<>(path)
,再将新的数组赋值给res,因为path回溯到最后一定为空
public static List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
dfs(root, targetSum, new ArrayList<>(), res);
return res;
}
public static void dfs(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> res){
path.add(root.val);
targetSum -= root.val;
//到叶子节点找到路径,添加到结果
if (root.left == null && root.right == null && targetSum == 0) {
//❗❗❗新创建一个数组给res赋值
res.add(new ArrayList<>(path));
}
//到叶子节点没有路径
if(root.left == null && root.right == null && targetSum != 0){
return;
}
if(root.left != null){
//System.out.println("L root:"+root.val+" root.left:"+root.left.val);
dfs(root.left, targetSum, path, res);
//System.out.print("L 回溯 root:"+root.val+" root.left:"+root.left.val+" "+path);
//❗❗❗必须要回溯
path.remove(path.size() - 1);
//System.out.print("----->"+path);
//System.out.println();
}
if(root.right != null){
//System.out.println("R root:"+root.val+" root.right:"+root.right.val);
dfs(root.right, targetSum, path, res);
//System.out.print("R 回溯 root:"+root.val+" root.right:"+root.right.val+" "+path);
//❗❗❗必须要回溯
path.remove(path.size() - 1);
//System.out.print("----->"+path);
//System.out.println();
}
}
106.从中序与后序遍历序列构造二叉树+105
- 本题算是比较难的二叉树题目了,大家先看视频来理解。
- 106.从中序与后序遍历序列构造二叉树,105.从前序与中序遍历序列构造二叉树 一起做,思路一样的
- 题目链接
- 视频讲解:https://www.bilibili.com/video/BV1vW4y1i7dn
- 文章讲解:https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html
105.递归代码
- 参考视频:https://b23.tv/NPXvK67
- 优化思路
- 通过哈希表直接在中序遍历中找根节点,不通过
for循环
- 把下标加到参数里,不需要新建数组再拷贝
- 通过哈希表直接在中序遍历中找根节点,不通过
/*
int[] preorder = {1,2,4,3,6,7};
int[] inorder = {4,2,1,6,3,7};
前序:中左右;中序:左中右
根 1
pre in
左 2,4 4,2
右 3,6,7 6,3,7
根 2
左 4
右 null
根 3
左 6
右 7
递归的问题
*/
public static TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0 || inorder.length == 0) return null;
//创建根节点
int rootValue = preorder[0];
TreeNode root = new TreeNode(rootValue);
//区分左右子树
for(int i = 0; i < inorder.length; i ++){
if(inorder[i] == rootValue){
//0 ~ i-1 是左子树
//i+1 ~ inorder.length-1 是右子树
//Arrays.copyOfRange()是左闭右开区间
int[] inLeft = Arrays.copyOfRange(inorder, 0, i);//[4, 2]
int[] inRight = Arrays.copyOfRange(inorder, i + 1, inorder.length);//[6, 3, 7]
//拆分前序遍历的数组
int[] preLeft = Arrays.copyOfRange(preorder, 1, i + 1);//[2, 4]
int[] preRight = Arrays.copyOfRange(preorder, i + 1, inorder.length);//[3, 6, 7]
root.left = buildTree(preLeft, inLeft);
root.right = buildTree(preRight, inRight);
break;
}
}
return root;
}
105.随想录代码
Map<Integer, Integer> map;
public TreeNode buildTree(int[] preorder, int[] inorder) {
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置
map.put(inorder[i], i);
}
return findNode(preorder, 0, preorder.length, inorder, 0, inorder.length); // 前闭后开
}
public TreeNode findNode(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd) {
// 参数里的范围都是前闭后开
if (preBegin >= preEnd || inBegin >= inEnd) { // 不满足左闭右开,说明没有元素,返回空树
return null;
}
int rootIndex = map.get(preorder[preBegin]); // 找到前序遍历的第一个元素在中序遍历中的位置
TreeNode root = new TreeNode(inorder[rootIndex]); // 构造结点
int lenOfLeft = rootIndex - inBegin; // 保存中序左子树个数,用来确定前序数列的个数
root.left = findNode(preorder, preBegin + 1, preBegin + lenOfLeft + 1,
inorder, inBegin, rootIndex);
root.right = findNode(preorder, preBegin + lenOfLeft + 1, preEnd,
inorder, rootIndex + 1, inEnd);
return root;
}
106.代码
与105类似