Created
July 23, 2021 20:03
-
-
Save Vibhu-Agarwal/888672f31fa050e848f5d72d2e7d2c0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
def inorder(root): | |
if root.left is not None: | |
inorder(root.left) | |
yield root | |
if root.right: | |
inorder(root.right) | |
def rev_inorder(root): | |
if root.right: | |
rev_inorder(root.right) | |
yield root | |
if root.left: | |
rev_inorder(root.left) | |
class Solution: | |
def findTarget(self, root: TreeNode, k: int) -> bool: | |
l, r = inorder(root), rev_inorder(root) | |
lk = next(l) | |
rk = next(r) | |
while lk is not rk: | |
sm = lk.val + rk.val | |
if sm == k: | |
return 1 | |
elif sm < k: | |
lk = next(l) | |
else: | |
rk = next(r) | |
return 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
def inorder(root): | |
if root.left is not None: | |
yield from inorder(root.left) | |
yield root | |
if root.right: | |
yield from inorder(root.right) | |
def rev_inorder(root): | |
if root.right: | |
yield from rev_inorder(root.right) | |
yield root | |
if root.left: | |
yield from rev_inorder(root.left) | |
class Solution: | |
def findTarget(self, root: TreeNode, k: int) -> bool: | |
l, r = inorder(root), rev_inorder(root) | |
lk = next(l) | |
rk = next(r) | |
while lk is not rk: | |
sm = lk.val + rk.val | |
if sm == k: | |
return 1 | |
elif sm < k: | |
lk = next(l) | |
else: | |
rk = next(r) | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment