herrDeng網內搜尋

自訂搜尋

Ads

2024年4月14日 星期日

C++ python速解左葉節點之和Leetcode 404 Sum of Left Leaves


C++ python速解左葉節點之和Leetcode 404  Sum of Left Leaves。影片中採最簡易解法preorder走訪遞迴,並設參數isLeft=0,其他解法詳見Leetcode連結。Python解請進,C++提供一行解。
--------
C++ python quick solution to Leetcode 404 Sum of Left Leaves. In the video, the simplest solution is preorder recursion, and the parameter isLeft=0 is used. For other solutions, please see the Leetcode link.
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
  9. def f(root, isLeft):
  10. if not root: return 0
  11. if not root.left and not root.right and isLeft: return root.val
  12. return f(root.left, True)+f(root.right, False)
  13. return f(root, False)
C++提供一行post-order解
  1. int sumOfLeftLeaves(TreeNode* root, bool isLeft=0) {
  2. return (root->left?sumOfLeftLeaves(root->left, 1):0)+
  3. (root->right?sumOfLeftLeaves(root->right, 0):0)+
  4. ((!root->left and !root->right and isLeft)?root->val:0);
  5. }

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章