連結:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
class Solution {
private int i = 0;//inorder
private int p = 0;//preorder
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, inorder, Integer.MIN_VALUE);
}
private TreeNode build(int[] preorder, int[] inorder, int stop) {
if (p >= preorder.length)
return null;
//剛好為parent時跳過換右樹
if (inorder[i] == stop) {
++i;
return null;
}
TreeNode node = new TreeNode(preorder[p++]);
node.left = build(preorder, inorder, node.val);
node.right = build(preorder, inorder, stop);
return node;
}
}
連結:https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/
class Solution {
int levelVal[] = new int[150];
public int maxLevelSum(TreeNode root) {
for (int i = 0; i < 150; ++i) {
levelVal[i] = Integer.MIN_VALUE;
}
find(root, 1);
int max = 1;
for (int i = 1; i < 150; ++i) {
if (levelVal[max] < levelVal[i]) max = i;
}
return max;
}
public void find(TreeNode root, int level) {
if (root == null) return;
if (levelVal[level] != Integer.MIN_VALUE) levelVal[level] += root.val; else levelVal[level] = root.val;
find(root.left, level + 1);
find(root.right, level + 1);
}
}