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.
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        def f(root, isLeft):
            if not root: return 0
            if not root.left and not root.right and isLeft: return root.val
            return f(root.left, True)+f(root.right, False)
        return f(root, False)
        
C++提供一行post-order解
 int sumOfLeftLeaves(TreeNode* root, bool isLeft=0) {
        return (root->left?sumOfLeftLeaves(root->left, 1):0)+
        (root->right?sumOfLeftLeaves(root->right, 0):0)+
        ((!root->left and !root->right and isLeft)?root->val:0);
    }
 

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章