1. 程式人生 > 其它 >Deepest Leaves Sum(C++層數最深葉子節點的和)

Deepest Leaves Sum(C++層數最深葉子節點的和)

技術標籤:C++LeetCode二叉樹c++leetcode

解題思路:

(1)先遍歷求出最深的深度值

(2)再遍歷一次,將最深的節點值相加

/**
 * 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 {
private:
    int max = 0,sum = 0;
    
public:
    void preorder(TreeNode *root,int h) {
        if(root!=NULL) {
            if(h>max) max = h;
            preorder(root->left,h+1);
            preorder(root->right,h+1);
        }
    }
    
    void getsum(TreeNode *root,int h) {
        if(root!=NULL) {
            if(h==max) sum+=root->val;
            getsum(root->left,h+1);
            getsum(root->right,h+1);
        }
    }
    
    int deepestLeavesSum(TreeNode* root) {
        int h = 0;
        preorder(root,h);
        getsum(root,h);
        return sum;
    }
};