Binary Search Tree

Problem Description

In computer science, a binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties: 
The left subtree of a node contains only nodes with keys less than the node's key. 
The right subtree of a node contains only nodes with keys greater than the node's key. 
The left and right subtree must each also be a binary search tree. 
There must be no duplicate nodes. 
Now you are given a binary tree, and the key on each node.
Please help to answer the question, what is the least number of nodes do we have to modify to adjust the binary tree to a BST? 
Notice, the key of a node can be modified to arbitrary real number.

Input

Multiple test cases. First line, an integer T ( 1 ≤ T ≤ 20 ), indicating the number of test cases. 
For each test case, there will first be an empty line. 
Then an integer n ( 1 ≤ n ≤ 5,000 ), indicating the number of nodes. You can assume nodes are numbered from 1 to n. After that, n lines follows. 
On each of the n lines, say line i, indicating the information of node i. There are three integers key_i, L_i, R_i ( |key_i| ≤ 1,000,000,000, 1 ≤ L_i, R_i ≤ n ), indicating the key, left child, right child of the node. If one node does not have the left/right child, L_i/R_i will be zero.

Ouput

For each test case, output a line. The answer is an integer m ( 0 <= m <= n - 1 ), indicating the least number of nodes we have to modify.

Sample Input

2

3
2 2 3
3 0 0
1 0 0

2
10 0 2
15 0 0

Sample Output

2
0

Hint

For test case 1, we can modify the key of node #2 to 1, and modify the key of node #3 to 3. 
For test case 2, we do not need any modification.

 

 1 #include <stdio.h>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int v[5100],l[5100],r[5100],num;
 7 int flag[5100],a[5100],dp[5100];
 8 
 9 void find_root(int x)//寻找树的根节点
10 {
11     if(flag[x]==1 || x==0) return;
12     flag[x]=1;
13     find_root(l[x]);
14     find_root(r[x]);
15 }
16 void dfs(int x)//中序遍历整棵树,把所有节点的权值存入a数组中
17 {
18     if(x==0) return;
19     dfs(l[x]);
20     a[num++]=v[x];
21     dfs(r[x]);
22 }
23 
24 int main()
25 {
26     int T,n,i,j;
27     int root;
28     scanf("%d",&T);
29     while(T--)
30     {
31         scanf("%d",&n);
32         for(i=1; i<=n; i++) scanf("%d %d %d",&v[i],&l[i],&r[i]);
33         memset(flag,0,sizeof(flag));
34         for(i=1; i<=n; i++)
35             if(!flag[i])
36             {
37                 root=i;
38                 find_root(i);
39             }
40         num=0;
41         dfs(root);
42 
43         for(i=0; i<=n; i++) dp[i]=1;
44         //求出数组a中最长递增子序列长度存入dp数组中
45         for(i=1; i<n; i++)
46             for(j=i-1; j>=0; j--)
47                 if(dp[i]<dp[j]+1 && a[i]>a[j]) dp[i]=dp[j]+1;
48 
49         printf("%d\n",n-*max_element(dp,dp+n));
50     }
51 
52     return 0;
53 }
View Code

 

posted @ 2013-05-18 23:54  1002liu  阅读(211)  评论(0编辑  收藏  举报