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.
[codes on Leetcode]https://leetcode.com/problems/sum-of-left-leaves/solutions/5018971/recursive-preordr-vs-iterative-dfs-0ms-beats-100/
[Tree & Graph Playlist]https://www.youtube.com/watch?v=9Lx7yr-tmfI&list=PLYRlUBnWnd5Kt0-3un43cwY6yT_il8NWe
# 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);
}
沒有留言:
張貼留言