[Leetcode] Binary tree--653. Two Sum IV - Input is a BST
Posted 安新
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Binary tree--653. Two Sum IV - Input is a BST相关的知识,希望对你有一定的参考价值。
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: 5 / 3 6 / \ 2 4 7 Target = 9 Output: True
Example 2:
Input: 5 / 3 6 / \ 2 4 7 Target = 28 Output: False
Solution:
#traverse the tree and using‘s hash to store visited node dic = {} def helperRecursive(root): if root is None: return False if (k - root.val) in dic: return True if root.val not in dic: dic[root.val] = 1 return helperRecursive(root.left) or helperRecursive(root.right) return helperRecursive(root)
以上是关于[Leetcode] Binary tree--653. Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode[110]-Balanced Binary Tree
LeetCode 110. Balanced Binary Tree 递归求解
[LeetCode]题解(python):110 Balanced Binary Tree
[Leetcode] Binary tree -- 617. Merge Two Binary Trees