leetcode 1302 the number of layers and the deepest leaf node

1. Topic

Give you a binary tree, you return to the deepest layers of the leaf nodes and.

Example:
Examples of binary tree

Input: root = [1,2,3,4,5, null, 6,7, null, null, null, null, 8]
output: 15

Note:
the tree node number between 1 and 10 ^ 4.
Value for each node between 1 and 100.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/deepest-leaves-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. My problem solution

Breadth-first traversal, traversal time record node value of each layer and, when the first layer and cleared, the last recorded case entry and is the result.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int deepestLeavesSum(TreeNode* root) {
        queue<TreeNode *> q;
        int res=0;
        if(root)q.push(root);
        while(!q.empty()){
            res=0;
            int len = q.size();
            for(int i=0;i<len;i++){
                if(q.front()->left)q.push(q.front()->left);
                if(q.front()->right)q.push(q.front()->right);
                res+=q.front()->val;
                q.pop();
            }
        }
        return res;
    }
};

3. someone else's problem solution

Depth-first traversal also, when implementing the layers as a parameter passed recursive.
Need to record two variables, a current is obtained and a maximum depth of the current tree.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int sum=0;
    int curDepth=-1;
public:
    int deepestLeavesSum(TreeNode* root) {
        dfs(root,0);
        return sum;
    }
    void dfs(TreeNode * root ,int depth){
        if(root==NULL)return;
        if(depth==curDepth){sum+=root->val;}
        else if(depth>curDepth){sum=root->val;curDepth=depth;}
        dfs(root->left,depth+1);
        dfs(root->right,depth+1);
    }
};

4. Summary and Reflection

(1) recursive depth-first search is simple, but time-consuming high;

Published 32 original articles · won praise 0 · Views 433

Guess you like

Origin blog.csdn.net/weixin_43951240/article/details/103864077