C++ 递归遍历+判断左叶子节点,效率不高,
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int res; 13 int sumOfLeftLeaves(TreeNode* root) { 14 DFS(root); 15 return res; 16 } 17 void DFS(TreeNode* root){ 18 if(root==NULL) return; 19 DFS(root->left); 20 if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL) 21 res+=root->left->val; 22 DFS(root->right); 23 } 24 };
更多答案参考大佬解答:
https://leetcode.com/problems/sum-of-left-leaves/discuss/244628/six-ways-to-solve-this-question
明天好好学习一下
原文地址:https://www.cnblogs.com/joelwang/p/10441021.html
时间: 2024-11-10 18:13:37