513.找树左下角的值
🔗题目链接:力扣
💡解题思路:迭代比递归简单许多,只需要记录最后一行第一个节点的数值就可以了。
代码如下:
//迭代法
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;
}
//递归法
int Deep = -1;
int value = 0;
public int findBottomLeftValue2(TreeNode root) {
value = root.val;
findLeftValue(root, 0);
return value;
}
private void findLeftValue (TreeNode root, int deep) {
//终止条件
if (root == null) return;
if (root.left == null && root.right == null) {
if (deep > Deep) {
value = root.val;
Deep = deep;
}
}
//单层循环逻辑
if (root.left != null) findLeftValue(root.left, deep + 1);
if (root.right != null) findLeftValue(root.right, deep + 1);
}
112. 路径总和
🔗题目链接:力扣
💡解题思路:回溯
1. 确定返回值类型:boolean
2. 确定终止条件:
不要去累加然后判断是否等于目标和,那么代码比较麻烦,可以用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。
如果最后count == 0,同时到了叶子节点的话,说明找到了目标和。
如果遍历到了叶子节点,count不为0,就是没找到。
3. 确定单层递归的逻辑
因为终止条件是判断叶子节点,所以递归的过程中就不要让空节点进入递归了。
递归函数是有返回值的,如果递归函数返回true,说明找到了合适的路径,应该立刻返回。
代码如下:
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
return findPath(root, targetSum - root.val);
}
private boolean findPath(TreeNode root, int count) {
if(root.left == null && root.right == null && count == 0) return true;
if(root.left == null && root.right == null && count != 0) return false;
if(root.left != null) {
if(findPath(root.left, count - root.left.val)) return true;
}
if(root.right != null) {
if(findPath(root.right, count - root.right.val)) return true;
}
return false;
}
106.从中序与后序遍历序列构造二叉树
🔗题目链接:力扣
💡解题思路:回溯
一共分几步:
-
第一步:如果数组大小为零的话,说明是空节点了。
-
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
-
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
-
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
-
第五步:切割后序数组,切成后序左数组和后序右数组
-
第六步:递归处理左区间和右区间
注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量。
代码如下:
Map<Integer, Integer> map;
public TreeNode buildTree(int[] inorder, int[] postorder) {
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return findNode(inorder, 0, inorder.length, postorder, 0, postorder.length);
}
public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
if (inBegin >= inEnd || postBegin >= postEnd) {
return null;
}
//找到后序遍历的最后一个元素在中序遍历中的位置
int rootIndex = map.get(postorder[postorder.length - 1]);
//构造节点
TreeNode root = new TreeNode(inorder[rootIndex]);
int leftOfLenth = rootIndex - inBegin;
root.left = findNode(inorder, inBegin, rootIndex, postorder, postBegin, postBegin + leftOfLenth);
root.right = findNode(inorder, rootIndex + 1, inEnd, postorder, postBegin +leftOfLenth, postEnd - 1);
return root;
}
📝今日心得
第三题好难,看视频看了几遍才理清楚,自己单独写还是不太行。
第二遍做第三题还是写不出来代码,看了答案之后勉强能默写出来,但是举一反三可能就不太行。
😭 一定要成为递归大佬!