PAT甲级1102 Invert a Binary Tree:[C++题解]反转二叉树、递归
生活随笔
收集整理的這篇文章主要介紹了
PAT甲级1102 Invert a Binary Tree:[C++题解]反转二叉树、递归
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目分析
- 題目鏈接
題目分析
反轉二叉樹這道題目特別出名!!!,是因為Homebrew這款Mac上大火的軟件的作者到google面試,就考了這道題。面試官說了下面這段話:你竟然連在白板上翻轉二叉樹都不會,還是滾吧。
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
Homebrew簡介
來源:維基百科
分析: 反轉二叉樹,這里用的遞歸的寫法,交換根結點的左右子樹。
先交換再遍歷左右子樹可以;
void dfs_reverse(int u){if(u == -1) return; //沒有兒子返回swap(l[u],r[u]); //交換左右子樹 dfs_reverse(l[u]); dfs_reverse(r[u]); }先遍歷左右子樹,再交換左右子樹也可以。
void dfs_reverse(int u){if(u == -1) return;dfs_reverse(l[u]); dfs_reverse(r[u]);swap(l[u],r[u]); //交換左右子樹}ac代碼
#include<bits/stdc++.h> using namespace std;const int N = 20;int l[N] ,r[N]; int q[N]; //數組模擬隊列 int n,root;bool has_father[N]; //看當前結點有無父節點,從而求根結點//翻轉二叉樹 void dfs_reverse(int u){if(u == -1) return;dfs_reverse(l[u]);dfs_reverse(r[u]);swap(l[u],r[u]); //交換左右子樹}//層次遍歷bfs void bfs(int u){int hh = 0 ,tt = 0;q[0] =u;while(hh<= tt){int t =q[hh++];if(l[t] != -1) q[++tt] = l[t];if(r[t] != -1 ) q[++ tt] = r[t];}cout<< q[0];for(int i=1;i<n;i ++) cout<<" "<<q[i];cout<<endl; }//中序遍歷 /*k用來統計輸出的個數,防止行末空格*/ void dfs( int u, int& k){//中序遍歷if(u == -1) return;dfs(l[u], k);cout<< u;if(++k !=n) cout<<" ";dfs(r[u] , k);}int main(){//左右兒子數組初始化為-1,表示沒有兒子memset(l,-1, sizeof l);memset(r ,-1, sizeof r);cin>> n;for(int i=0; i<n; i++) {char lc, rc;cin>> lc >> rc;if(lc != '-') l[i] = lc -'0',has_father[l[i]] =true;if(rc != '-') r[i] =rc - '0',has_father[r[i]] =true;}root =0;while(has_father[root]) root++;dfs_reverse(root); //反轉二叉樹bfs(root); //層次遍歷int k =0; //防止行末空格dfs(root , k); //中序遍歷 }題目鏈接
PAT甲級1102 Invert a Binary Tree
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的PAT甲级1102 Invert a Binary Tree:[C++题解]反转二叉树、递归的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT甲级1099 Build A Bi
- 下一篇: PAT甲级1110 Complete B