第四講 樹(中)

来源:http://www.cnblogs.com/VincentValentine/archive/2017/05/10/6838843.html
-Advertisement-
Play Games

04 樹4:是否同一棵二叉搜索樹 Description: 給定一個插入序列就可以唯一確定一棵二叉搜索樹。然而,一棵給定的二叉搜索樹卻可以由多種不同的插入序列得到。例如分別按照序列{2, 1, 3}和{2, 3, 1}插入初始為空的二叉搜索樹,都得到一樣的結果。於是對於輸入的各種插入序列,你需要判斷 ...


04-樹4:是否同一棵二叉搜索樹
Description:

給定一個插入序列就可以唯一確定一棵二叉搜索樹。然而,一棵給定的二叉搜索樹卻可以由多種不同的插入序列得到。例如分別按照序列{2, 1, 3}和{2, 3, 1}插入初始為空的二叉搜索樹,都得到一樣的結果。於是對於輸入的各種插入序列,你需要判斷它們是否能生成一樣的二叉搜索樹。

Input:

輸入包含若幹組測試數據。每組數據的第1行給出兩個正整數N≤10和L,分別是每個序列插入元素的個數和需要檢查的序列個數。第2行給出N個以空格分隔的正整數,作為初始插入序列。最後L行,每行給出N個插入的元素,屬於L個需要檢查的序列。

簡單起見,我們保證每個插入序列都是1到N的一個排列。當讀到N為0時,標誌輸入結束,這組數據不要處理。

Output:

對每一組需要檢查的序列,如果其生成的二叉搜索樹跟對應的初始序列生成的一樣,輸出“Yes”,否則輸出“No”。

SampleInput:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

SampleOutput:

Yes
No
No

Codes:
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode* Tree;
struct TreeNode
{
    int data;
    Tree left,right;
    int flag;
}; 

Tree NewNode(int data)
{
    Tree T = (Tree)malloc(sizeof(struct TreeNode));
    T->data = data;
    T->left = T->right = NULL;
    T->flag = 0;
    return T;
}

Tree Insert(Tree T,int data)
{
    if( !T )
        T = NewNode(data);
    else {
        if(data > T->data)
            T->right = Insert(T->right, data);
        else
            T->left = Insert(T->left, data);
    }
    return T;
}

Tree MakeTree(int N)
{
    Tree T;
    int data;
    scanf("%d",&data);
    T = NewNode(data);
    for(int i = 1; i < N; i++) {
        scanf("%d",&data);
        T = Insert(T,data);
    }
    return T;
}

bool check (Tree T,int data)
{
    if(T->flag) {
        if(data < T->data)
            return check(T->left,data);
        else if(data > T->data)
            return check(T->right,data);
    }else {
        if(data == T->data) {    //是要找的結點 
            T->flag = 1;
            return true;
        }
        else return false;            //不是 不一致 
    }
}

int Judge(Tree T,int N)
{
    int data;
    int flag = 0;//0代表目前仍一致 1代表已經不一致
    scanf("%d",&data);
    if(data != T->data)    //    判斷根節點是否一致 
        flag = 1; 
    else T->flag = 1;
    for(int i = 1; i < N; i++) {    //確保L讀完 
        scanf("%d",&data);
        if( (!flag) && (!check(T,data)) )    //不一致 
            flag = 1;
    }
    if(flag)     //不一致 
        return 0;
    else return 1;
}

void ResetT(Tree T)//清除T中各結點的flag標記
{
    if(T->left)
        ResetT(T->left);
    if(T->right)
        ResetT(T->right);
    T->flag = 0;
} 

void FreeTree(Tree T) //釋放T的空間
{
    if(T->left)
        FreeTree(T->left);
    if(T->right)
        FreeTree(T->right);
    free(T);
} 

int main()
{
    int N, L;
    Tree T;
    scanf("%d",&N);
    while(N) {
        scanf("%d",&L);
        T = MakeTree(N);
        for(int i = 0; i < L; i++) {
            if(Judge(T, N))
                printf("Yes\n");
            else
                printf("No\n");
            ResetT(T);        //清除T中的標記flag 
        } 
        FreeTree(T);
        scanf("%d",&N);
    }
    
    return 0;
}
PAT-1066:Root of AVL Tree.
Description:

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output:

For each test case, print ythe root of the resulting AVL tree in one line.

SampleInput1:

5
88 70 61 96 120

SampleOutput1:

70

SampleInput2:

7
88 70 61 96 120 90 65

SampleOutput2:

88

Codes:
#include <cstdio>
#include <algorithm>
using namespace std;
struct node{
    node *left, *right;
    int v, w;
    node(int value, node* l, node* r) : v(value), left(l), right(r), w(0) {}
};
node *nil = new node(0, NULL, NULL);
node *head = nil;
void leftrotate(node *&head){
    node *t = head->right;
    head->right = t->left;
    t->left = head;
    head = t;
    head->left->w = max(head->left->right->w, head->left->left->w) + 1;
    head->w = max(head->right->w, head->left->w) + 1;
}
void rightrotate(node *&head){
    node *t = head->left;
    head->left = t->right;
    t->right = head;
    head = t;
    head->right->w = max(head->right->right->w, head->right->left->w) + 1;
    head->w = max(head->right->w, head->left->w) + 1;
}
void insert(node *&head, int v){
    if (head == nil){
        head = new node(v, nil, nil);
    }else if (v > head->v){
        insert(head->right, v);
        if (2 == head->right->w - head->left->w){
            if (v > head->right->v){
                leftrotate(head);
            }else{
                rightrotate(head->right);
                leftrotate(head);
            }
        }
    }else{
        insert(head->left, v);
        if (2 == head->left->w - head->right->w){
            if (v <= head->left->v){
                rightrotate(head);
            }else{
                leftrotate(head->left);
                rightrotate(head);
            }
        }
    }
    head->w = max(head->left->w, head->right->w) + 1;
}
int main()
{
    int n, a;
    scanf("%d", &n);
    while (n--){
        scanf("%d", &a);
        insert(head, a);
    }
    printf("%d\n", head->v);
    return 0;
}
PAT-1064:Complete Binary Search Tree.
Description:

A Binary Search Tree (BST) is recursively defined as a binary tree 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 or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output:

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

SampleInput:

10
1 2 3 4 5 6 7 8 9 0

SampleOutput:

6 3 8 1 5 7 9 0 2 4

Codes:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int n;
vector<int> preOrder;

void PreTraversal(int root)
{
    if (root > n)
        return;
    PreTraversal(2 * root);
    preOrder.push_back(root);
    PreTraversal(2 * root + 1);
}

int main()
{
    cin >> n;

    int num[1001], levelOrder[1001];
    for (int i = 0; i < n; i++)
        cin >> num[i];

    sort(num, num + n);
    PreTraversal(1);
    for (int i = 0; i < preOrder.size(); i++)
        levelOrder[preOrder[i]] = num[i];
    for (int i = 1; i < n; i++)
        cout << levelOrder[i] << " ";
    cout << levelOrder[n];
        
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 字典表示一種複雜的數據結構,這種數據結構允許按照某個鍵來訪問元素。字典也稱為映射或散列表。 字典的主要特性是能根據鍵快速查找值。也可以自由添加和刪除元素,這有點像List<T>(http://www.cnblogs.com/afei-24/p/6824791.html),但沒有在記憶體中移動後續元素的 ...
  • 1 /// 2 /// 短鏈生成 3 /// 4 public class ShortUrlBuilder 5 { 6 private static readonly string[] Chars = 7 { "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h"... ...
  • 一、確定多線程的結束時間,thread的IsAlive屬性 在多個線程運行的背景下,瞭解線程什麼時候結束,什麼時候停止是很有必要的。 案例:老和尚念經計時,2本經書,2個和尚念,一人一本,不能撕破,最短時間念完,問老和尚們念完經書最短需要多長時間。 分析:首先在開始念經的時候給計時,記為A,最後在記 ...
  • MVVM的目標之一就是為瞭解耦View和ViewModel。View負責視圖展示,ViewModel負責業務邏輯處理,儘量保證 View.xaml.cs中的簡潔,不包含複雜的業務邏輯代碼。 但是在實際情況中是View和ViewModel之間的交互方式還是比較複雜的,View和ViewModel的分離 ...
  • 最近趁著不忙,在構思一個搭建一個開源的完整項目,至於原因以及整個項目框架後邊文章我再說明。既然要起一個完整的項目,那麼數據倉儲訪問就必不可少,這篇文章我主要介紹這個新項目(OSS.Core)中我對倉儲層的簡單思考和實現過程(當前項目還處在搭建階段),主要集中在以下幾個方面: 1. 數據倉儲層的需求 ...
  • 作業二:多級菜單 (1)三級菜單 (2)可以次選擇進入各子菜單 (3)所需新知識點:列表、字典 要求:輸入b返回上一層,輸入q退出整個程式 思路:三級菜單第一級別是省,第二級別是市,第三級別是縣,用戶可以根據內容選擇要查看的東西,因此要使用while迴圈來進行操作,要有兩層迴圈,第一層是b負責的,第 ...
  • 1、 縱觀大局,卻也精於細節 階段性瀏覽,不要碰到一點小知識就死磕,把握一個度。 2、 註重練習(複習) 複習或者強化練習太重要了,不然太容易忘記了。 ...
  • 說到文件上傳我們要做到: 1.引入兩個包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar 2.將form改為上傳文件模式:enctype="multipart/form-data" 3.開始編寫相關代碼 這裡會用到幾個關鍵的類:磁碟文件工廠Disk ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...