31 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.

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

分析

題意:給定一顆二叉搜索樹,找出以特定值爲根節點的子樹;若該值不存在,則返回null.

簡單的深度遍歷,注意利用二叉搜索樹的特性即可:左<根<右

解答

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
    	// 遞歸終點,root爲空說明不存在,root.val==val說明已找到
        if(root==null || root.val==val)
            return root;
        // 根據二叉搜索樹的特性,比較目標值決定遍歷方向
        if(root.val>val)
            return searchBST(root.left,val);
        else
            return searchBST(root.right,val);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章