给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
示例 1:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
解法一:递归法,每次递归返回当前节点所处层数和以该节点为根节点的子树的最深叶子节点和:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
return recursion(root, 1).first;
}
private:
pair<int, int> recursion(TreeNode *node, int layer) {
if (node->left == nullptr && node->right == nullptr) {
return {node->val, layer};
}
pair<int, int> leftPair;
pair<int, int> rightPair;
if (node->left) {
leftPair = recursion(node->left, layer + 1);
}
if (node->right) {
rightPair = recursion(node->right, layer + 1);
}
if (leftPair.second > rightPair.second) {
return leftPair;
} else if (leftPair.second < rightPair.second) {
return rightPair;
}
return {leftPair.first + rightPair.first, leftPair.second};
}
};
如果树的节点数为n,树的高度为h,此代码时间复杂度为O(n),空间复杂度为O(h)。
解法二:循环法,借助队列实现,每次计算一层的和:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int deepestLeavesSum(TreeNode* root) {
queue<TreeNode *> q;
q.push(root); // 向队列尾加入元素
int sum = 0;
while (!q.empty()) {
sum = 0;
int sz = q.size();
for (int i = 0; i < sz; ++i) {
TreeNode *curNode = q.front();
sum += curNode->val;
if (curNode->left) {
q.push(curNode->left);
}
if (curNode->right) {
q.push(curNode->right);
}
q.pop(); // 从队列头删除元素
}
}
return sum;
}
};
如果树的节点数为n,树的宽度为w,此代码时间复杂度为O(n),空间复杂度为O(w)。