给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
思路简单,注意到深度改变时,sum清零
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* dfs(struct TreeNode* root,int deepth,int * sum,int *max_deepth) { if(root == NULL) return NULL; if(deepth > (*max_deepth)) { (*max_deepth) = deepth; (*sum) = 0; //guiling heihei } struct TreeNode *left,*right; left = dfs(root->left,deepth+1,sum,max_deepth); right = dfs(root->right,deepth+1,sum,max_deepth); //没有&&&& if(left == NULL && right == NULL && deepth == (*max_deepth)) (*sum) += root->val; return root; } int deepestLeavesSum(struct TreeNode* root){ int sum = 0; if(root == NULL) return 0; int max_deepth = 0; dfs(root,0,&sum,&max_deepth); //&&&& return sum; }