在leetCode看到一題目java
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.node
Example 1:spa
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: TrueExample 2:code
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
因而用js造一棵樹,而後嘗試實現blog
/** * [tree 樹] * val 節點值 * leftTree 左樹(null表明沒有左樹) * rightTree 右樹(null表明沒有右樹) */ var myTree = { val: 5, leftTree:{ val: 3, leftTree:{ val: 2, leftTree: null, rightTree: null }, rightTree: { val: 4, leftTree: null, rightTree: null } }, rightTree:{ val: 6, leftTree: null, rightTree: { val: 7, leftTree: null, rightTree: null }, } } //主方法 function findTarget(tree, k) { //用於存儲遍歷過的節點的值 var set = []; //查找 return find(tree, k, set); } //查找方法 function find(tree, k, set){ //若是節點爲空直接返回false,不須要考慮根節點爲空的狀況,由於不可能 if(null == tree){ return false; } //看集合中是否包含 目標數(k)-節點值(root.val) if(set.indexOf(k-tree.val) > -1){ return true; } //將當前節點值存進集合 set.push(tree.val); //對本樹的左右節點進行判斷,遞歸 return find(tree.leftTree, k, set) || find(tree.rightTree, k, set); } //testing console.log(findTarget(myTree, 14));
java版的遞歸
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 //主方法 12 public boolean findTarget(TreeNode root, int k) { 13 //用於存儲遍歷過的節點的值 14 HashSet<Integer> set = new HashSet<Integer>(); 15 //查找 16 return find(root, k, set); 17 } 18 19 //查找方法 20 public boolean find(TreeNode root, int k, HashSet<Integer> set){ 21 //若是節點爲空直接返回false,不須要考慮根節點爲空的狀況,由於不可能 22 if(null == root){ 23 return false; 24 } 25 26 //看集合中是否包含 目標數(k)-節點值(root.val) 27 if(set.contains(k-root.val)){ 28 return true; 29 } 30 31 //將當前節點值存進集合 32 set.add(root.val); 33 34 //對本樹的左右節點進行判斷,遞歸 35 return find(root.left, k, set) || find(root.right, k, set); 36 } 37 }