classSolution {public:intsumOfLeftLeaves(TreeNode*root) {if(!root || (!root->left && !root->right))return0;intres =0; stack<TreeNode*>s; s.push(root);while(!s.empty()) { TreeNode*t =s.top(); s.pop();if(t->left && !t->left->left && !t->left->right) res += t->...
1、题目描述 2、问题分析 对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可。 3、代码 1intsumOfLeftLeaves(TreeNode*root) {2if(root ==NULL)3return0;4intans =0;5if(root->left !=NULL) {6if(root->left->left == NULL && root->left->right ==NULL)...
404. Sum of Left LeavesEasy Topics Companies Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 24 ...
Sum of Left Leaves Find the sum of all left leaves in a given binary tree. Example: 题目:将一棵树上所有的左叶子节点进行求和。 思路:关键在于找到终止条件,如果一棵树为空,返回0;如果左子树存在且为叶子结点,则将其值加入到sum中去,然后再递归去求左子树中左叶子节点之和和右子树中左叶子节点之和...
int left = 0, right = 0; if (head.left != null && head.left.left == null && head.left.right == null) { left = head.left.val; } else { left = sumOfLeftLeaves(head.left); } right = sumOfLeftLeaves(head.right); return left + right; ...
Leetcode: Sum of Left Leaves,Recursion:是不是left子数完全由bottom往上第二层决定,如果是left子树且是叶子节点,那么就是leftleaves,parent得告诉child是不是在left子树BFS:
Find the sum of all left leaves in a given binary tree think about this, when we reached leaf, how are we gonna to know if it is left leaf or not? of course we can modify the iterate version of preorder traverse, it’s very simple. ...
left.val; } int sum = midSum + leftSum + rightSum; return sum; } } //层序遍历法 // 层序遍历迭代法 class Solution { public int sumOfLeftLeaves(TreeNode root) { int sum = 0; if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>();//双向队列也行 queue.offer...
0404 Sum of Left Leaves Go 56.2% Easy 0405 Convert a Number to Hexadecimal Go 46.1% Easy 0406 Queue Reconstruction by Height 72.8% Medium 0407 Trapping Rain Water II 47.4% Hard 0408 Valid Word Abbreviation 34.8% Easy 0409 Longest Palindrome Go 54.6% Easy 0410 Split Array Largest Sum...
404 Sum of Left Leaves Easy Solution 405 ? ? Solution 406 Queue Reconstruction by Height Medium Solution 407 Trapping Rain Water II Hard Solution 408 Valid Word Abbreviation Easy Solution 409 Longest Palindrome Easy Solution 410 Split Array Largest Sum Hard Solution 412 Fizz Buzz Easy Solution 413...