玩命加载中 . . .

700-二叉搜索树中的搜索


LeetCode 700. Search in a Binary Search Tree

LeetCode-700

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null.


Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

method: 递归

递归结束条件:如果节点为空,说明没找到,返回空节点;如果等于val,说明找到,也返回当前节点
单层逻辑:当前节点值比val大,往左子树找,比val小,往右子树找

TreeNode* searchBST(TreeNode* root, int val) {
    if (!root || root->val == val) return root;
    if (root->val > val) return searchBST(root->left, val);
    else return searchBST(root->right, val);
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录