• 欢迎光临~

# 105和106 写了1个多小时,终于悟了

### 513. 找树左下角的值

``````public int findBottomLeftValue(TreeNode root) {
travel(root, 0);
}

private int maxDepth = -1;

public void travel(TreeNode cur, int depth) {
if (depth > maxDepth && cur.left == null && cur.right == null) {
maxDepth = depth;
}
if (cur.left != null) {
travel(cur.left, depth + 1);
}
if (cur.right != null) {
travel(cur.right, depth + 1);
}
}
``````

### 112. 路径总和

``````public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
targetSum -= root.val;
return targetSum == 0;
}
boolean left = false;
if (root.left != null) {
left = hasPathSum(root.left, targetSum - root.val);
}
boolean right = false;
if (root.right != null) {
right = hasPathSum(root.right, targetSum - root.val);
}
return left || right;
}
``````

### 106. 从中序与后序遍历序列构造二叉树

``````        Map<Integer, Integer> map = new HashMap<>();

public TreeNode buildTree(int[] inorder, int[] postorder) {
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return buildTree(inorder, 0, inorder.length, postorder, 0, inorder.length);
}

// 这个 inStart,代表的是,左边(右边)中序遍历的开始, poStart是 左边(右边) 后序遍历的开始
public TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int poStart, int poEnd) {
if (inStart >= inEnd || poStart >= poEnd) {
return null;
}
int mid = postorder[poEnd - 1];
TreeNode root = new TreeNode(mid);
Integer midIndex = map.get(mid);
int leftInStart = inStart, leftInEnd = midIndex, leftLength = leftInEnd - leftInStart;
int rightInStart = midIndex + 1, rightInEnd = inEnd;

int leftPoStart = poStart, leftPoEnd = poStart + leftLength;
int rightPoStart = leftPoEnd, rightPoEnd = poEnd - 1;
root.left = buildTree(inorder, leftInStart, leftInEnd, postorder, leftPoStart, leftPoEnd);
root.right = buildTree(inorder, rightInStart, rightInEnd, postorder, rightPoStart, rightPoEnd);
return root;
}
``````