欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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;
}