package _06binary_tree.day18._01find_bottom_left_value;
public class Solution {
int result = 0;
int maxDepth = Integer.MIN_VALUE;
// 递归
public int findBottomLeftValue(TreeNode root) {
findLeftValue(root, 0);
return result;
}
private void findLeftValue(TreeNode node, int depth) {
// 找到叶子节点
if (node != null && node.left == null && node.right == null) {
// 判断是否是深度最大的叶子节点
if (depth > maxDepth) {
maxDepth = depth;
result = node.val;
return;
}
}
if(node.left != null){
findLeftValue(node.left,depth + 1);
}
if(node.right != null){
findLeftValue(node.right,depth + 1);
}
return;
}
}
// 迭代:层序遍历
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int result = 0;
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == 0) result = node.val;
if(node.left != null)queue.offer(node.left);
if(node.right != null)queue.offer(node.right);
}
}
return result;
}
package _06binary_tree.day18._02has_path_sum;
public class Solution {
// 递归
public 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){
if(hasPathSum(root.left,targetSum)){
return true;
}
}
if(root.right != null){
if(hasPathSum(root.right,targetSum)){
return true;
}
}
return false;
}
// 简洁版
public boolean hasPathSum2(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));
}
}
package _06binary_tree.day18._03build_tree;
import java.util.HashMap;
import java.util.Map;
public 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.put(inorder[i], i);
}
// 左闭右开
return buildNode(inorder, 0, inorder.length, postorder, 0, postorder.length);
}
private TreeNode buildNode(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
if (inStart >= inEnd || postStart >= postEnd) return null; // 空节点
int rootValue = postorder[postEnd - 1];
int rootIndex = map.get(rootValue);
TreeNode root = new TreeNode(rootValue);
int leftLen = rootIndex - inStart; // 中序左数组的长度
root.left = buildNode(inorder, inStart, rootIndex, // 中序数组的分割点去掉(rootIndex处)
postorder, postStart, postStart + leftLen);
root.right = buildNode(inorder, rootIndex + 1, inEnd,
postorder, postStart + leftLen, postEnd - 1); // 后序数组的分割点去掉(postEnd处)
return root;
}
}