浙大pat | 浙大pat 牛客网甲级 1010 Build A Binary Search Tree (30) 二叉搜索树

题目描述

A Binary Search Tree (BST) is recursively defined as a binarytree which has the following properties:
The left subtree of a node contains only nodes with keys less than the node'skey.
The right subtree of a node contains only nodes with keys greater than or equalto the node's key.
Both the left and right subtrees must also be binary search trees.

Given the structure of a binary tree and a sequence of distinctinteger keys, there is only one way to fill these keys into the tree so thatthe resulting tree satisfies the definition of a BST.  You are supposed to output the level ordertraversal sequence of that tree.  The sampleis illustrated by Figure 1 and 2.

 

 



输入描述:

Each input file contains one test case.  For each case, the first line gives apositive integer N (<=100) which is the total number of nodes in thetree.  The next N lines each contains theleft and the right children of a node in the format "left_indexright_index", provided that the nodes are numbered from 0 to N-1, and 0 isalways the root.  If one child ismissing, then -1 will represent the NULL child pointer.  Finally N distinct integer keys are given inthe last line.




输出描述:

For each test case, print in one line the level order traversalsequence of that tree.  All the numbersmust be separated by a space, with no extra space at the end of the line.



输入例子:

9

1 6

2 3

-1 -1

-1 4

5 -1

-1 -1

7 -1

-1 8

-1 -1

73 45 11 58 82 25 67 38 42



输出例子:

58 25 82 11 38 67 45 73 42

哎,要是考试的时候每一题都是这个难度就好了,这一题可以说是想当的简单,题目条例清晰,没有陷阱,也没有隐藏条件,并且让你干什么一清二楚

首先使用一个DFS得到每个节点左儿子个数和右儿子个数,

然后将输入数字排序,在使用一个DFS2来将排序之后的数字分配给每个节点,

之后使用一次BFS按照层次遍历的顺序输出每个节点的值,这样样就能够得到最终的结果

这一题条理非常的清晰

这里需要注意的是在统计左儿子节点和右儿子节点的数量的时候返回值要加一,这表示当前节点也参与了统计

以后在做二叉树的题目的时候使用多次BFS和DFS然后将每次遍历的结果统计起来,可能会有意想不到的好结果!

注意这个单词level order traversal sequence 表示的层次序遍历序列,也就是层次遍历,广度优先遍历,traversal表示横越,遍历的意思

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;
pair<int, int> leftOrRightCount[103];
int theEdges[103][2] = { -1 };
int everyNum[103];
int DFS1(int t)
{
	if (t == -1) return 0;
	int left = DFS1(theEdges[t][0]);
	int right = DFS1(theEdges[t][1]);
	leftOrRightCount[t] = make_pair(left, right);
	return left + right+1;
}
void DFS2(int left, int right, int t,vector<int> &num)
{
	if (t == -1) return;
	everyNum[t] = num[left+ leftOrRightCount[t].first];
	DFS2(left, left + leftOrRightCount[t].first - 1, theEdges[t][0], num);
	DFS2(left + leftOrRightCount[t].first + 1, right, theEdges[t][1], num);
}

int main()
{
	int N;
	int a, b;
	cin >> N;
	vector<int> num(N);
	for (int i = 0; i < N; i++)
	{
		cin >> a >> b;
		theEdges[i][0] = a;
		theEdges[i][1] = b;
	}
	for (int i = 0; i < N; i++)
	{
		cin >> num[i];
	}
	sort(num.begin(), num.end());
	DFS1(0);
	DFS2(0, N - 1, 0, num);
	queue<int> theQueue;
	theQueue.push(0);
	b = 1;
	while (!theQueue.empty())
	{
		a = theQueue.front();
		theQueue.pop();
		cout << everyNum[a];
		if ((b++) != N) cout << " ";
		if (theEdges[a][0] != -1) theQueue.push(theEdges[a][0]);
		if (theEdges[a][1] != -1) theQueue.push(theEdges[a][1]);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 二叉搜索树Binary Search Tree):是一棵空树或者具有下列性质的二叉树:若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值;若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值;它的左右子树也分别为二叉搜索树。 中序遍历序列:对于任意一棵二叉树,中序遍历的结果都是一个序列,这个序列称为中序遍历序列。 因此,判断一棵二叉树是否为二叉搜索树,可以先进行中序遍历,再判断遍历结果是否为升序序列。 以下是 Python 代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorderTraversal(root: TreeNode) -> List[int]: res = [] if not root: return res res.extend(inorderTraversal(root.left)) res.append(root.val) res.extend(inorderTraversal(root.right)) return res def isBST(root: TreeNode) -> bool: res = inorderTraversal(root) for i in range(1, len(res)): if res[i] <= res[i-1]: return False return True ``` 其中,`TreeNode` 是二叉树的节点类,`inorderTraversal` 函数是实现二叉树中序遍历的递归函数,`isBST` 函数是判断二叉树是否为二叉搜索树的函数。 ### 回答2: 要实现这个函数,首先我们可以使用递归的方式对二叉树进行中序遍历,即先遍历左子树,再访问根节点,最后遍历右子树。遍历过程中将遍历到的节点值保存到一个数组中。 接下来,我们需要判断该数组是否是按升序排列的,即判断是否是一棵二叉搜索树。我们可以遍历数组,依次比较相邻的节点值,如果前一个节点的值大于等于后一个节点的值,则认为不是二叉搜索树。反之,如果整个数组都符合这个条件,则认为是一个二叉搜索树。 以下是一个简单的实现代码: ``` class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorderTraversal(root): if not root: return [] result = [] inorder(root, result) return result def inorder(root, result): if not root: return inorder(root.left, result) result.append(root.val) inorder(root.right, result) def isBST(root): inorder_result = inorderTraversal(root) for i in range(1, len(inorder_result)): if inorder_result[i] <= inorder_result[i-1]: return False return True ``` 这个函数的时间复杂度是O(n),其中n是二叉树中节点的数量,因为我们需要遍历每个节点并将节点的值保存到数组中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值