代码随想录训练营第18天|513.找树左下角的值,112. 路径总和 113.路径总和ii,106.从中序与后序遍历序列构造二叉树,105.从前序与中序遍历序列构造二叉树
)
513.找树左下角的值
文章
思路
层序遍历,换行时保留新行第一个节点的值,结束时返回这个值。
代码
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int i, n, res;
res = 0;
TreeNode curr;
while (!queue.isEmpty()) {
n = queue.size();
for (i = 0; i < n; ++i) {
curr = queue.poll();
if (i == 0) {
res = curr.val;
}
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
}
return res;
}
}
112.路径总和 +113.路径总和II
文章
思路
深度优先搜索,递归到下一层时,targetsum要减去当前节点的val
112.题是搜到即返回
113.题要维护当前节点对应的路径,搜到叶子节点要保存
代码
// 112.
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && root.val == targetSum) {
return true;
}
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
//113.
class Solution {
private List<Integer> path = new ArrayList<>();
private List<List<Integer>> paths = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root, targetSum);
return paths;
}
public void dfs(TreeNode root, int targetSum) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null && root.val == targetSum) {
// path.add(root.val);
paths.add(new ArrayList<>(path));
path.remove(path.size() - 1);
return;
}
dfs(root.left, targetSum - root.val);
dfs(root.right, targetSum - root.val);
path.remove(path.size() - 1);
return;
}
}
106.从中序与后序遍历序列构造二叉树 + 105.从前序与中序遍历序列构造二叉树
文章
思路
上周日做过剑指Offer 07.重建二叉树,跟105题是一样的。
所以思路不写了,直接看这个链接
代码
// 106.
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
Stack<TreeNode> st = new Stack<>();
int i, j, n;
n = inorder.length;
j = n - 1;
TreeNode root, node;
root = new TreeNode(postorder[n - 1]);
st.push(root);
for (i = n - 2; i > -1; --i) {
node = st.peek();
if (inorder[j] != node.val) {
node.right = new TreeNode(postorder[i]);
st.push(node.right);
} else {
while (!st.isEmpty() && st.peek().val == inorder[j]) {
// System.out.println(" " + st.peek().val + ", " + inorder[j]);
node = st.pop();
--j;
}
node.left = new TreeNode(postorder[i]);
st.push(node.left);
}
}
return root;
}
}
// 105.
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
Stack<TreeNode> st = new Stack<>();
int i, j, n;
j = 0;
n = inorder.length;
TreeNode root, node;
root = new TreeNode(preorder[0]);
st.push(root);
for (i = 1; i < n; ++i) {
node = st.peek();
if (node.val != inorder[j]) {
node.left = new TreeNode(preorder[i]);
st.push(node.left);
} else {
while(!st.isEmpty() && st.peek().val == inorder[j]) {
node = st.pop();
++j;
}
node.right = new TreeNode(preorder[i]);
st.push(node.right);
}
}
return root;
}
}
总结
上周做过的题忘得好快
哪里是if,哪里是while要总结
真的很不想写递归啊,栈空间那么宝贵,迭代法从堆里开空间多好