leetcode543. 二叉树的直径

二叉搜索树

http://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b

leetcode543. 二叉树的直径

#include<vector>
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(nullptr), right(nullptr){}
};

TreeNode* insertBST(TreeNode* root, int x) {
	if (root == nullptr) {
		root = new TreeNode(x);
		return root;
	}
	if (x < root->val) {
		root->left = insertBST(root->left, x);
	}
	else if (x > root->val) {
		root->right = insertBST(root->right, x);
	}
	return root;
}

bool isSameBst(TreeNode* root1, TreeNode* root2) {
	if (root1 == nullptr && root2 == nullptr) {
		return true;
	}
	else if ((root1 == nullptr && root2 != nullptr) || (root1 != nullptr && root2 == nullptr)) {
		return false;
	}
	int val1 = root1->val;
	int val2 = root2->val;
	if (val1 != val2)
		return false;
	if (isSameBst(root1->left, root2->left) == false || isSameBst(root1->right, root2->right) == false) {
		return false;
	}
	return true;
}

int main() {
	int n;
	cin >> n;
	string str;
	cin >> str;
	TreeNode* root1 = nullptr;
	//1. build BST
	for (int i = 0; i < str.size(); i++) {
		root1 = insertBST(root1, (int)str[i]);
	}
	//2. 判断新序列是否为二叉树
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		TreeNode* root2 = nullptr;
		for (int i = 0; i < s.size(); i++) {
			root2 = insertBST(root2, (int)s[i]);
		}
		if (isSameBst(root1, root2)) {
			cout << "YES" << endl;
		}
		else {
			cout << "NO" << endl;
		}
	}
	return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务