653. Two Sum IV - Input is a BST*

653. Two Sum IV - Input is a BST*

https://leetcode.com/problems/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

C++ 实现 0

前序遍历, 似乎除了元素 unique 这个条件比较重要外, 对于树是否为 BST, 并不重要. 我们借鉴 Two Sum 的思路, 使用哈希表保存被访问过的元素, 然后将依次访问树中的每个节点, 判断 k - root->val 是否在哈希表中. 如果存在的话, 那么说明树中存在两个节点的和等于 target.

class Solution {
public:
    unordered_set<int> record;
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        if (record.count(k - root->val)) return true;
        record.insert(root->val);
        return findTarget(root->left, k) || findTarget(root->right, k);
    }
};

C++ 实现 1

前序遍历二分搜索树, 用哈希表保存结果, 最后参照 1. Two Sum* 求解.

class Solution {
private:
    void dfs(TreeNode *root, unordered_set<int> &record) {
        if (!root)
            return;

        record.insert(root->val);
        dfs(root->left, record);
        dfs(root->right, record);
    }
public:
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> record;
        dfs(root, record);

        for (auto &val : record)
            if (record.count(k - val) && (k - val) != val)
                return true;
        return false;
    }
};

C++ 实现 2

二分搜索树的中序遍历得到的结果是有序的, 然后参考 167. *Two Sum II - Input array is sorted 利用对撞指针求解.

class Solution {
private:
    void InOrder(TreeNode *root, vector<int> &record) {
        if (!root)
            return;

        InOrder(root->left, record);
        record.push_back(root->val);
        InOrder(root->right, record);
    }

public:
    bool findTarget(TreeNode* root, int k) {
        vector<int> record;
        InOrder(root, record);
        // 然后使用 Two Sum
        int l = 0, r = record.size() - 1;
        while (l < r) {
            if (record[l] + record[r] == k)
                return true;
            else if (record[l] + record[r] < k)
                l ++;
            else
                r --;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个比较复杂的问题,需要较长的代码实现。以下是一个可能的Java实现,供您参考: ``` import java.util.Scanner; // 定义二叉排序树结点类 class BSTNode { int key; BSTNode left; BSTNode right; public BSTNode(int key) { this.key = key; left = null; right = null; } } // 定义二叉排序树类 class BST { private BSTNode root; public BST() { root = null; } // 插入结点 public void insert(int key) { root = insert(root, key); } private BSTNode insert(BSTNode node, int key) { if (node == null) { node = new BSTNode(key); return node; } if (key < node.key) { node.left = insert(node.left, key); } else { node.right = insert(node.right, key); } return node; } // 删除结点 public void delete(int key) { root = delete(root, key); } private BSTNode delete(BSTNode node, int key) { if (node == null) { return node; } if (key < node.key) { node.left = delete(node.left, key); } else if (key > node.key) { node.right = delete(node.right, key); } else { if (node.left == null) { node = node.right; } else if (node.right == null) { node = node.left; } else { BSTNode temp = findMin(node.right); node.key = temp.key; node.right = delete(node.right, temp.key); } } return node; } private BSTNode findMin(BSTNode node) { while (node.left != null) { node = node.left; } return node; } // 查找结点 public boolean search(int key) { return search(root, key); } private boolean search(BSTNode node, int key) { if (node == null) { return false; } if (key == node.key) { return true; } else if (key < node.key) { return search(node.left, key); } else { return search(node.right, key); } } // 中序遍历输出 public void inorder() { inorder(root); } private void inorder(BSTNode node) { if (node != null) { inorder(node.left); System.out.print(node.key + " "); inorder(node.right); } } } // 主程序 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BST bst = new BST(); int choice = -1; while (choice != 0) { // 显示菜单 System.out.println("查找子系统"); System.out.println("****************************************"); System.out.println("* 1------顺 序 查 找 *"); System.out.println("* 2------二 分 查 找 *"); System.out.println("* 3------二 叉 排 序 树 *"); System.out.println("* 0------返 回 *"); System.out.println("****************************************"); System.out.print("请选择菜单号(0--3):"); choice = scanner.nextInt(); switch (choice) { case 1: // 顺序查找 System.out.print("请输入要查找的数:"); int key = scanner.nextInt(); int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; boolean found = false; for (int i = 0; i < arr.length; i++) { if (arr[i] == key) { found = true; break; } } if (found) { System.out.println("找到了"); } else { System.out.println("没找到"); } break; case 2: // 二分查找 System.out.print("请输入要查找的数:"); key = scanner.nextInt(); arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int low = 0; int high = arr.length - 1; found = false; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == key) { found = true; break; } else if (arr[mid] < key) { low = mid + 1; } else { high = mid - 1; } } if (found) { System.out.println("找到了"); } else { System.out.println("没找到"); } break; case 3: // 二叉排序树 System.out.print("请输入要插入的数(以0结束):"); key = scanner.nextInt(); while (key != 0) { bst.insert(key); System.out.print("请输入要插入的数(以0结束):"); key = scanner.nextInt(); } System.out.print("请输入要查找的数:"); key = scanner.nextInt(); found = bst.search(key); if (found) { System.out.println("找到了"); } else { System.out.println("没找到"); } System.out.print("请输入要删除的数:"); key = scanner.nextInt(); bst.delete(key); bst.inorder(); System.out.println(); break; case 0: // 返回 break; default: System.out.println("输入错误,请重新输入"); break; } } scanner.close(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值