LeetCode之653. Two Sum IV - Input is a BST

* 这题属于Two Sum题,将BST中根遍历存到数组当中,转换为数组的Two Sum问题即可 *

C # 代码

public bool FindTarget(TreeNode root, int k)
        {
            List<int> lst = new List<int>();
            BST2Lst(root,ref lst);
            int i = 0;
            int j = lst.Count-1;
            while(i<j)
            {
                if(lst[i] + lst[j] == k)
                {
                    return true;
                }
                if( lst[i]+lst[j] < k)
                    i++;
                else 
                    j--;
            }

            return false;


        }
        public  void  BST2Lst(TreeNode root, ref List<int> lst)
        {
            if(root == null)
                return ;

            BST2Lst(root.left, ref lst);
            lst.Add(root.val);
            BST2Lst(root.right, ref lst);

        }

python 3代码

class Solution:
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        lst = []
        self.BST2Lst(root, lst)
        i = 0
        j = len(lst)-1
        while(i<j):
            flag = lst[i]+lst[j]
            if flag == k :
                return True
            if flag < k:
                i += 1
            else:
                j -= 1
        return False

    def BST2Lst(self, root, lst):
        if root == None:
            return
        self.BST2Lst(root.left, lst)
        lst.append(root.val)
        self.BST2Lst(root.right, lst)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值