问题:
难度:medium
说明:
给出一个二叉树,然后将二叉树最深的子叶值相加,返回总和。
题目连接:https://leetcode.com/problems/deepest-leaves-sum/
输入范围:
- The number of nodes in the tree is in the range
[1, 104]
. 1 <= Node.val <= 100
输入案例:
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
Example 2:
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19
我的代码:
dfs或者bfs就可以了,bfs性能还比较差。
Java:
class Solution {
private int deep = 0, maxDeep = 0, total = 0;
public int deepestLeavesSum(TreeNode root) {
if(root == null) return 0;
deep ++;
if(deep > maxDeep) {
maxDeep = deep;
total = 0;
}
if(root.left != null) {
deepestLeavesSum(root.left);
deep --;
}
if(root.right != null) {
deepestLeavesSum(root.right);
deep --;
}
if(deep == maxDeep) total += root.val;
return total;
}
// private static TreeNode[][] stack = new TreeNode[2][2500];
// public int deepestLeavesSum(TreeNode root) {
// int pre = 0, cur = 1, preIdx = 0, curIdx = 0, total = 0;
// if(root != null) stack[pre][preIdx ++] = root;
// while(preIdx != 0) {
// for(int i = 0; i < preIdx; i ++) {
// TreeNode node = stack[pre][i];
// if(node.left != null) stack[cur][curIdx ++] = node.left;
// if(node.right != null) stack[cur][curIdx ++] = node.right;
// }
// if(curIdx == 0)
// for(int i = 0; i < preIdx; i ++) total += stack[pre][i].val;
// pre ^= 1;
// cur ^= 1;
// preIdx = curIdx;
// curIdx = 0;
// }
// return total;
// }
}
C++:
class Solution {
public:
int deep = 0, maxDeep = 0, total = 0;
int deepestLeavesSum(TreeNode* root) {
if(!root) return 0;
deep ++;
if(deep > maxDeep) {
maxDeep = deep;
total = 0;
}
if(root->left != nullptr) {
deepestLeavesSum(root->left);
deep --;
}
if(root->right != nullptr) {
deepestLeavesSum(root->right);
deep --;
}
if(deep == maxDeep) total += root->val;
return total;
}
// TreeNode* stack[2][2500];
// int deepestLeavesSum(TreeNode* root) {
// int pre = 0, cur = 1, preIdx = 0, curIdx = 0, total = 0;
// if (root) stack[pre][preIdx++] = root;
// while (preIdx) {
// for (int i = 0; i < preIdx; i++) {
// TreeNode* node = stack[pre][i];
// if (node->left) stack[cur][curIdx++] = node->left;
// if (node->right) stack[cur][curIdx++] = node->right;
// }
// if (!curIdx)
// for (int i = 0; i < preIdx; i++) total += stack[pre][i]->val;
// pre ^= 1;
// cur ^= 1;
// preIdx = curIdx;
// curIdx = 0;
// }
// return total;
// }
};