一句话总结,还是那个树~
原题链接:513 找树左下角的值
这题不难,不知道怎么混上的中等难度。只需要利用广度优先遍历,用一个队列保存每一层的节点,然后在不停迭代中最后一轮第一个节点的值即是所求值,返回即可。
class Solution {
int maxDepth = 0;
int depth = 0;
int ans = 0;
public int findBottomLeftValue(TreeNode root) {
if(root == null) return 0;
depth++;
if(root.left == null && root.right == null){
if(depth > maxDepth){
maxDepth = depth;
ans = root.val;
}
}
findBottomLeftValue(root.left);
findBottomLeftValue(root.right);
depth--;
return ans;
}
}
原题链接:112 路径总和
首先特判两个情况,即root == null时返回false,root.left == null && root.right == null 时返回root.val == targetSum=。然后递归的找左子树与右子树是否存在一个val == targetSum - root.val即可。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == targetSum;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
原题链接:113 路径总和II
这题其实利用到了回溯算法。代码不会写,但还是能理解。先附上。
class Solution {
List<List<Integer>> ans = new LinkedList<>();
List<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root, targetSum);
return ans;
}
void dfs(TreeNode root, int target) {
if (root == null) return;
path.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) ans.add(new LinkedList<>(path));
dfs(root.left, target);
dfs(root.right, target);
path.removeLast();
}
}
原题链接:106 从中序与后序遍历序列构造二叉树
思想跟手推中序与后序遍历序列构造是一样的。手写不会,附上随想录解法,容易理解。
class Solution {
Map<Integer, Integer> map; // 方便根据数值查找位置
public TreeNode buildTree(int[] inorder, int[] postorder) {
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置
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[postEnd - 1]); // 找到后序遍历的最后一个元素在中序遍历中的位置
TreeNode root = new TreeNode(inorder[rootIndex]); // 构造结点
int lenOfLeft = rootIndex - inBegin; // 保存中序左子树个数,用来确定后序数列的个数
root.left = findNode(inorder, inBegin, rootIndex,
postorder, postBegin, postBegin + lenOfLeft);
root.right = findNode(inorder, rootIndex + 1, inEnd,
postorder, postBegin + lenOfLeft, postEnd - 1);
return root;
}
}