PAT(Advanced)1115 Counting Nodes in a BST 先序遍歷 C++實現

PAT(Advanced)甲級1115 Counting Nodes in a BST 先序遍歷 C++實現

題目鏈接

1115 Counting Nodes in a BST

題目大意

給定一個序列,建立二叉搜索樹,根據題目給出二叉排序樹定義,在二叉搜索樹中的的任一節點其左子樹的所有節點關鍵字小於等於該節點關鍵字,其左子樹的所有節點關鍵字大於該節點關鍵字,其左右子樹也必須是一棵二叉搜索樹,可以存在關鍵字相同的節點

算法思路

根據題意,先建立二叉搜索樹

BST::BST(vector<int>& sequence) {
    root = NULL;
    level.resize(sequence.size());
    for (vector<int>::iterator it = sequence.begin(); it != sequence.end(); it++) {
        insert(root, *it);
    }
    depth = 0;
    preOrderTraverse(root, 0);
}

void BST::insert(Node* &p, int value) {
	// 第一個參數爲指針的引用,改變當前結點父親節點(若有)的對應子樹指針,方便插入
    if (p == NULL) {
    	// 找到空節點
        p = new Node(value);
        return;
    }
    // 若小於等於當前結點關鍵字則到左子樹中遞歸查找位置,否則在右子樹中查找
    insert((p->data >= value ? p->left : p->right), value);
}

先序遍歷,遞歸地計算每一層有多少結點,存入level數組

void BST::preOrderTraverse(Node *p, int currentLevel) {
    if (p == NULL) {
        return;
    }
    depth = max(depth, currentLevel);
    level[currentLevel]++;
    preOrderTraverse(p->left, currentLevel + 1);
    preOrderTraverse(p->right, currentLevel + 1);
}

AC代碼

/*
author : eclipse
email  : [email protected]
time   : Sun Jun 28 20:30:05 2020
*/
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node *left;
    Node *right;
    Node(int value) : data(value), left(NULL), right(NULL) {}
};

class BST {
private:
    Node *root;
    vector<int> level;
    int depth;
    void insert(Node* &p, int value);
    void preOrderTraverse(Node *p, int currentLevel);
public:
    BST(vector<int>& sequence);
    void print();
};

BST::BST(vector<int>& sequence) {
    root = NULL;
    level.resize(sequence.size());
    for (vector<int>::iterator it = sequence.begin(); it != sequence.end(); it++) {
        insert(root, *it);
    }
    depth = 0;
    preOrderTraverse(root, 0);
}

void BST::insert(Node* &p, int value) {
    if (p == NULL) {
        p = new Node(value);
        return;
    }
    insert((p->data >= value ? p->left : p->right), value);
}

void BST::preOrderTraverse(Node *p, int currentLevel) {
    if (p == NULL) {
        return;
    }
    depth = max(depth, currentLevel);
    level[currentLevel]++;
    preOrderTraverse(p->left, currentLevel + 1);
    preOrderTraverse(p->right, currentLevel + 1);
}

void BST::print() {
    printf("%d + %d = %d", level[depth], level[depth - 1], level[depth] + level[depth - 1]);
}

int main(int argc, char const *argv[]) {
    int N;
    scanf("%d", &N);
    vector<int> sequence;
    sequence.resize(N);
    for (int i = 0; i < sequence.size(); i++) {
        scanf("%d", &sequence[i]);
    }
    BST *bst = new BST(sequence);
    bst->print();
    return 0;
}

樣例輸入

9
25 30 42 16 20 20 35 -5 28

樣例輸出

2 + 4 = 6

鳴謝

PAT

最後

  • 由於博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章