본문 바로가기

tree4

[LeetCode] Sum of Left Leaves 파이썬 (Tree) class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ def sumOfLeftLeavesHelper(root, is_left): if not root: return 0 if not root.left and not root.right: return root.val if is_left else 0 return sumOfLeftLeavesHelper(root.left, True) + sumOfLeftLeavesHelper(root.right, False) return sumOfLeftLeavesHelper(root, False) leaf 노드 까지 탐색한다. left일 경우에만 + 출처: .. 2021. 4. 15.
[LeetCode] Lowest Common Ancestor 파이썬 (tree) class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s 2021. 4. 7.
[LeetCode] Invert Binary Tree 파이썬(recursion) recursively # 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 invertTree(self, root: TreeNode) -> TreeNode: def recu(node): if node == None: return recu(node.left) recu(node.right) node.left, node.right = node.right, node.left recu(root) return root iteratively cl.. 2021. 4. 5.
[LeetCode] Maximum Depth of Binary Tree 파이썬 (recursion) 40ms class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return an integer def maxDepth(self, root): if root is None: return 0 else: return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 출처:github.com/jiapengwen/LeetCode/blob/master/Python/maximum-depth-of-binary-tree.py class Solution: def maxDepth(se.. 2021. 3. 31.