700. Search in a Binary Search Tree
程序员文章站
2022-06-08 09:28:36
...
找到以val为根的子树
#include <iostream>
#include <algorithm>
#include "vector"
#include "string"
#include "set"
#include "queue"
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* searchBST(TreeNode* root, int val)
{
TreeNode* node = root;
if (node == NULL)
{
return NULL;
}
if (node->val == val)
{
return node;
}
else if (node->val > val)
{
return searchBST(node->left, val);
}
//else if(node->val < val)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else
{
return searchBST(node->right, val);
}
}
int main()
{
TreeNode *n1 = new TreeNode(0);
TreeNode *n2 = new TreeNode(0);
TreeNode *n3 = new TreeNode(0);
TreeNode *n4 = new TreeNode(0);
TreeNode *n5 = new TreeNode(0);
n1->val = 4; n1->left = n2; n1->right = n3;
n2->val = 2; n2->left = n4; n2->right =n5;
n3->val = 7; n3->left = NULL; n3->right = NULL;
n4->val = 1; n4->left = NULL; n3->right = NULL;
n5->val = 3; n5->left = NULL; n5->right = NULL;
searchBST(n1, 2);
system("pause");
return 0;
}
上一篇: 八、IO优化(7)减少IO竞争
下一篇: Vue+Element-ui实现返回顶部
推荐阅读
-
荐 Java刷题笔记15:不同的二叉搜索树( Unique Binary Search Trees)
-
Convert Sorted Array to Binary Search Tree
-
二分查找(binary search)java实现及时间复杂度
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
96. Unique Binary Search Trees
-
POJ 1757 Binary Search G++
-
Binary Search:349. Intersection of Two Arrays