513.找树左下角的值本题递归偏难,反而迭代简单属于模板题, 两种方法掌握一下
题目链接/文章讲解/视频讲解:代码随想录
本题要找出树的最后一行的最左边的值。此时大家应该想起用层序遍历是非常简单的了,反而用递归的话会比较难一点。
迭代法
本题使用层序遍历再合适不过了,比递归要好理解得多!
只需要记录最后一行第一个节点的数值就可以了。
/**
* 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 int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
int result = -1;
if(root != null){
queue.offer(root);
}
while(!queue.isEmpty()){
int size = queue.size();
result = queue.peek().val;// 记录最后一行第一个元素
while(size-- > 0){
TreeNode temp = queue.poll();
if(temp.left != null) queue.offer(temp.left);
if(temp.right != null) queue.offer(temp.right);
}
}
return 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 {
int maxDepth = Integer.MIN_VALUE;// 全局变量 记录最大深度
int result = 0; // 全局变量 最大深度最左节点的数值
public int findBottomLeftValue(TreeNode root) {
result = root.val;
findLeftValue(root, 0);
return result;
}
public void findLeftValue(TreeNode node, int depth){
if (node == null) return;
if(node.left == null && node.right == null){
if(depth > maxDepth){
maxDepth = depth;// 更新最大深度
result = node.val;// 最大深度最左面的数值
}
}
// 中
if(node.left != null){// 左
depth++; // 深度加一
findLeftValue(node.left, depth);
depth--;// 回溯,深度减一
}
if(node.right != null){// 右
depth++;// 深度加一
findLeftValue(node.right, depth);
depth--;// 回溯,深度减一
}
}
}
路径总和
递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:
- 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(这种情况就是本文下半部分介绍的113.路径总和ii)
- 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (这种情况我们在236. 二叉树的最近公共祖先中介绍)
- 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
如果最后count == 0,同时到了叶子节点的话,说明找到了目标和。
如果遍历到了叶子节点,count不为0,就是没找到。
注意回溯的实现,count在什么位置减才能符合题意(递归法)
/**
* 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 boolean hasPathSum(TreeNode root, int targetSum) {
return traversal(root, targetSum);
}
public boolean traversal(TreeNode cur, int count){
if(cur == null) return false;
// 需要减掉本层节点的值,此时并没有改变上一层节点的count,实际上形成了回溯
count -= cur.val;
// 叶子结点
if(cur.left == null && cur.right == null && count == 0){
return true;
}else if(cur.left == null && cur.right == null && count != 0){
return false;
}
if(cur.left != null){
// count -= cur.left.val; 不能在此时减去节点值
if(traversal(cur.left, count)) return true;
// count += cur.left.val;已经在上一层实现回溯,不需要在本层再回溯
}
if(cur.right != null){
// count -= cur.right.val; 不能在此时减去节点值
if(traversal(cur.right, count)) return true;
// count += cur.right.val;已经在上一层实现回溯,不需要在本层再回溯
}
return false;
}
}
迭代
此时栈里一个元素不仅要记录该节点指针,还要记录从头结点到该节点的路径数值总和。
用pair结构来存放这个栈里的元素。定义为:pair<TreeNode*, int>
pair<节点指针,路径数值>
这个为栈里的一个元素。
也可以用两个栈保存这两个数据,同时入栈、出栈
class solution {
public boolean haspathsum(treenode root, int targetsum) {
if(root == null) return false;
stack<treenode> stack1 = new stack<>();
stack<integer> stack2 = new stack<>();
stack1.push(root);
stack2.push(root.val);
while(!stack1.isempty()) {
int size = stack1.size();
for(int i = 0; i < size; i++) {
treenode node = stack1.pop();
int sum = stack2.pop();
// 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
if(node.left == null && node.right == null && sum == targetsum) {
return true;
}
// 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
if(node.right != null){
stack1.push(node.right);
stack2.push(sum + node.right.val);
}
// 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
if(node.left != null) {
stack1.push(node.left);
stack2.push(sum + node.left.val);
}
}
}
return false;
}
}
113. 路径总和ii
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
113.路径总和ii要遍历整个树,找到所有路径,所以递归函数不要返回值!
用迭代方式记录所有路径比较麻烦,不适合
/**
* 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<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;// 非空判断
List<Integer> path = new LinkedList<>();
preorderdfs(root, targetSum, res, path);
return res;
}
// 递归函数不需要返回值,因为我们要遍历整个树
public void preorderdfs(TreeNode cur, int count, List<List<Integer>> res, List<Integer> path){
path.add(cur.val); // 把节点放进路径
// 遇到了叶子节点
if (cur.left == null && cur.right == null) {
if (count - cur.val == 0) {// 遇到了叶子节点且找到了和为sum的路径
res.add(new ArrayList<>(path));
}
return; // // 遇到叶子节点而没有找到合适的边(如果和不为 count),直接返回
}
if (cur.left != null) {// 左 (空节点不遍历)
preorderdfs(cur.left, count - cur.val, res, path);// 递归
path.remove(path.size() - 1); // 回溯
}
if (cur.right != null) {// 右 (空节点不遍历)
preorderdfs(cur.right, count - cur.val, res, path);// 递归
path.remove(path.size() - 1); // 回溯
}
}
}
从中序与后序遍历序列构造二叉树
前序和中序,后序和中序都可以构造二叉树,前序和后序不行,因为左右挨在一起,没办法找到分割点。中序在中间帮我们把左右区间隔开了,这样才能知道左区间和右区间分别是什么,然后才能去分割左右区间
通过后序找到中间节点是哪个,使用中间节点就可以在中序中切割左右子树,使用左区间和右区间再去切割后序,在切割后的数组中,再去寻找中间节点......
-
第一步:如果数组大小为零的话,说明是空节点了。
-
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
-
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
-
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
-
第五步:切割后序数组,切成后序左数组和后序右数组
-
第六步:递归处理左区间和右区间
每层递归定义了新的vector(就是数组),既耗时又耗空间
用下标索引写出的代码版本:(思路是一样的,只不过不用重复定义vector了,每次用下标索引来分割)
/**
* 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 TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder.length == 0 || inorder.length == 0)
return null;
// 左闭右开的原则
return buildHelper(inorder, 0, inorder.length, postorder, 0, postorder.length);
}
// 中序区间:[inorderBegin, inorderEnd),后序区间[postorderBegin, postorderEnd)
private TreeNode buildHelper(int[] inorder, int inorderStart, int inorderEnd, int[] postorder, int postorderStart, int postorderEnd){
//第一步:如果数组大小为零的话,说明是空节点了。
if(postorderStart == postorderEnd) return null;
//第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。后序遍历数组最后一个元素,就是当前的中间节点
int rootvalue = postorder[postorderEnd - 1];
TreeNode root = new TreeNode(rootvalue);
// 叶子节点
if(postorderEnd- postorderStart == 1) return root;
//第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
int delimiterIndex;
for(delimiterIndex = 0; delimiterIndex < inorderEnd; delimiterIndex++){
if(inorder[delimiterIndex] == rootvalue) break;
}
//第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组,按左闭右开切)
// 左中序区间,左闭右开区间:[leftInorderBegin, leftInorderEnd)=[inorderStart, delimiterIndex)
int leftInorderStart = inorderStart;
int leftInorderEnd = delimiterIndex;
// 右中序区间,左闭右开[rightInorderBegin, rightInorderEnd)=[delimiterIndex + 1, inorderEnd)
int rightInorderStart = delimiterIndex + 1;
int rightInorderEnd = inorderEnd;
//第五步:切割后序数组,切成后序左数组和后序右数组(中序数组大小一定是和后序数组的大小相同的)
// 左后序区间,左闭右开区间,注意这里使用了左中序数组大小作为切割点:[leftPostorderBegin, leftPostorderEnd)=[postorderStart, postorderStart + 左子树大小)
int leftPostorderStart = postorderStart;
int leftPostorderEnd = postorderStart + (leftInorderEnd - leftInorderStart);// postorderStart + 左子树宽度;终止位置是 需要加上 中序区间的大小size
// 右后序区间,左闭右开[rightPostorderBegin, rightPostorderEnd)=[postorderStart + 左子树大小, postorderEnd - 1) 最后一个节点是中间的父节点,因此减去
int rightPostorderStart = leftPostorderEnd;
int rightPostorderEnd = postorderEnd - 1;// postorder 舍弃末尾元素,因为这个元素就是中间节点,已经用过了
//第六步:递归处理左区间和右区间
root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart, leftPostorderEnd);
root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart, rightPostorderEnd);
return root;
}
}
105.从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
本题和106是一样的道理。只是后序换为前序,稍微改动一些代码
/**
* 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 TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null) return null;
return buildTreeHelper(preorder, 0, preorder.length, inorder, 0, inorder.length);
}
private TreeNode buildTreeHelper(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd){
if(preStart == preEnd) return null;
int rootVal = preorder[preStart];
TreeNode root = new TreeNode(rootVal);
if(preEnd- preStart == 1) return root;
int rootIndex;
for(rootIndex = 0; rootIndex < inEnd; rootIndex++){
if(inorder[rootIndex] == rootVal) break;
}
int leftInorderStart = inStart;
int leftInorderEnd = rootIndex;
int rightInorderStart = rootIndex + 1;
int rightInorderEnd = inEnd;
int leftPreorderStart = preStart + 1;
int leftPreorderEnd = preStart + 1 + leftInorderEnd - leftInorderStart;
int rightPreorderStart = leftPreorderEnd;
int rightPreorderEnd = preEnd;
root.left = buildTreeHelper(preorder, leftPreorderStart, leftPreorderEnd, inorder, leftInorderStart, leftInorderEnd);
root.right = buildTreeHelper(preorder, rightPreorderStart, rightPreorderEnd, inorder, rightInorderStart, rightInorderEnd);
return root;
}
}