LeetCode-700. Search in a Binary Search Tree

网友投稿 558 2022-08-25

LeetCode-700. Search in a Binary Search Tree

LeetCode-700. Search in a Binary Search Tree

​​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 3And 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​​.

题解:非递归解法

class Solution {public: TreeNode* searchBST(TreeNode* root, int val) { TreeNode *p = root; while (p){ if (p->val == val){ break; } else if (p->val > val){ p = p->left; } else if (p->val < val){ p = p->right; } } if (!p){ return NULL; } return p; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:编程能力七段论
下一篇:LeetCode-301. Remove Invalid Parentheses
相关文章

 发表评论

暂时没有评论,来抢沙发吧~