513. 找树左下角的值
public int findBottomLeftValue(TreeNode root) {
travel(root, 0);
return answer;
}
private int maxDepth = -1;
private int answer = 0;
public void travel(TreeNode cur, int depth) {
if (depth > maxDepth && cur.left == null && cur.right == null) {
maxDepth = depth;
answer = cur.val;
}
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;
}
标签:right,int,root,inorder,left,小时,null,106,105
From: https://www.cnblogs.com/Chain-Tian/p/17011576.html