Problem
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.
ExampleExample 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/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean findTarget(TreeNode root, int k) { Queuequeue = new LinkedList (); Set set = new HashSet<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode cur = queue.poll(); if (set.contains(k-cur.val)) return true; set.add(cur.val); if (cur.left != null) queue.offer(cur.left); if (cur.right != null) queue.offer(cur.right); } return false; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/69362.html
摘要:思路思路遍歷的時候,先把節點存起來,并且與每一個值相加,判斷是否等于所需值。用函數判斷與所求數字之差是否在數組內。否則,遍歷子節點。最終代碼若覺得本文章對你有用,歡迎用愛發電資助。 D89 653. Two Sum IV - Input is a BST 題目鏈接 653. Two Sum IV - Input is a BST 題目分析 給定一個二叉樹以及一個目標數字,判斷能不能通過...
摘要:在線網站地址我的微信公眾號完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個題。這是項目地址歡迎一起交流學習。 這篇文章記錄我練習的 LeetCode 題目,語言 JavaScript。 在線網站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號: showImg(htt...
1. Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. #### 1. 例子 Inp...
Problem Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, whil...
摘要:原題網址題意在二叉搜索樹當中找到離最近的個數。解題思路由于二叉搜索數的中序遍歷是有序的,比如例子中的樹,中序遍歷為。 原題網址:https://leetcode.com/problems... Given a non-empty binary search tree and a target value, find?k?values in the BST that are closes...
閱讀 3335·2021-11-22 12:04
閱讀 2719·2019-08-29 13:49
閱讀 492·2019-08-26 13:45
閱讀 2252·2019-08-26 11:56
閱讀 1011·2019-08-26 11:43
閱讀 604·2019-08-26 10:45
閱讀 1277·2019-08-23 16:48
閱讀 2166·2019-08-23 16:07