脚本宝典收集整理的这篇文章主要介绍了

leetcode讲解–700. Search in a Binary Search Tree

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。

题目

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

For example,

Given the tree:
        4
       / 
      2   7
     / 
    1   3

And the value to search: 2
You should return this subtree:

      2     
     /    
    1   3

In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.

Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.

题目地址

讲解

要注意一下的是,如果我们searchBST作为递归函数,我们就要返回一个TreeNode类型,虽然返回,但我们不一定会用到。如果我们找到了,就把treeNode标记为结果结点。

Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private TreeNode treeNode;
    public TreeNode searchBST(TreeNode root, int val) {
        if(root==null){
            return treeNode;
        }
        if(root.val == val){
            treeNode = root;
        }
        searchBST(root.left, val);
        searchBST(root.right, val);
        return treeNode;
    }
}

总结

以上是脚本宝典为你收集整理的

leetcode讲解–700. Search in a Binary Search Tree

全部内容,希望文章能够帮你解决

leetcode讲解–700. Search in a Binary Search Tree

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过