js java 给定一个目标值,在一棵树中找是否有两个节点的值之和等于目标值

在leetCode看到一题目

 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

于是用js造一棵树,然后尝试实现

/**
         * [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 }
原文地址:https://www.cnblogs.com/lzs-888/p/8875032.html