PAT甲级1115 Counting Nodes in a BST (30分):[C++题解] 递归建二叉搜索树、dfs求一层结点数量
生活随笔
收集整理的這篇文章主要介紹了
PAT甲级1115 Counting Nodes in a BST (30分):[C++题解] 递归建二叉搜索树、dfs求一层结点数量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目分析
- 題目鏈接
題目分析
分析
首先本題給定的二叉搜索樹的定義和其他地方的不同。本題小于等于的是左子樹,右子樹是大于根結點的。
然后說一下做題的思路。
給定一串數據,讓構造二叉搜索樹。 先想一想怎么存二叉樹,想用左兒子數組l[ ] 和右兒子數組 r[ ] 來存。這樣就得從根結點一直遞歸下去,其實給定的第一個數就是根結點。
建樹的過程其實還是一個遞歸。比較待插入的值和當前這個結點的大小關系,如果是小于等于,就插入到左邊;如果是大于當前結點,就插入到右邊。
對于求倒數兩層的結點數量,統計每一層的結點數用的是dfs,沒用bfs的原因是還多寫隊列,代碼更長一點。相比之下dfs代碼短很多,每層的結點數量存在cnt [ ] 數組中。
下面是根據一串數據遞歸建造二叉搜索樹的代碼
/* insert用來構造二叉搜索樹 u:結點下標 w:權重 */ void insert(int& u ,int w){//如果遍歷到某個點發現是空的,就生成新的結點,插入進來// u == 0表示空結點if(u == 0){u = ++ idx;v[u] = w;}//否則的話當前結點有值,比對一下插入左邊還是右邊else if( w <= v[u]) insert(l[u], w);else insert(r[u], w); }需要記錄一下,每來一個數據都是從根結點比下來的,小于等于根結點就往左,大于就往右。這樣的代價是用了一個根結點,兩個兒子數組。
AC代碼
#include<bits/stdc++.h> using namespace std;const int N = 1010;int n; int l[N] ,r[N]; int v[N]; //權值 int idx; //當前用到的編號,idx從1開始int cnt[N];//每層節點的數量 int max_depth; //最大層數/* insert用來構造二叉搜索樹 u:結點下標 w:權重 */ void insert(int& u ,int w){//如果遍歷到某個點發現是空的,就生成新的結點,插入進來// u == 0表示空結點if(u == 0){u = ++ idx;v[u] = w;}//否則的話當前結點有值,比對一下插入左邊還是右邊else if( w <= v[u]) insert(l[u], w);else insert(r[u], w); }//dfs深度優先搜索,求每一層的結點數 void dfs( int u, int depth){if( u == 0) return;cnt[depth] ++; //depth這一層的結點數量++max_depth = max(max_depth, depth);dfs(l[u],depth+1);dfs(r[u],depth+1); } int main(){cin >> n;int root = 0;for ( int i =1; i<= n; i ++){int w;cin>> w;insert(root, w);//根結點下標是1}dfs(root, 0); //從根結點開始,根結點是第0層int n1 = cnt[max_depth] ,n2 = cnt[max_depth -1];printf("%d + %d = %d",n1,n2,n1+n2);}題目鏈接
PAT甲級1115 Counting Nodes in a BST (30分)
總結
以上是生活随笔為你收集整理的PAT甲级1115 Counting Nodes in a BST (30分):[C++题解] 递归建二叉搜索树、dfs求一层结点数量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT甲级1110 Complete B
- 下一篇: PAT甲级1119 Pre- and P