国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Leetcode 117. Populating Next Right Pointers in Each Node II

2019-11-14 11:25:56
字體:
供稿:網(wǎng)友

Follow up for PRoblem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space. For example, Given the following binary tree,

1 / / 2 3 / / /4 5 7

After calling your function, the tree should look like:

1 -> NULL / / 2 -> 3 -> NULL / / /4-> 5 -> 7 -> NULL

s思路: 1. o(1)的空間,注定只能用iterative的方法了。參考https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution/6 2. 由于不規(guī)則的樹結(jié)構(gòu),所以需要用pre,cur來找到新的連接關系的兩端;還需要一個head表示每層的起點。三個指針的interplay在代碼里面寫得很清楚。每次把head賦給cur,然后根據(jù)cur->left、cur->right是否存在來更新連接:如果cur->left存在,又看pre是否已經(jīng)存在:不存在則這個節(jié)點就是head,且pre=cur->left;存在則就把這個節(jié)點作為pre的next;對cur->right也同樣判斷。 3. 多體會!

//class Solution {public: void connect(TreeLinkNode *root) { // TreeLinkNode* horizon=NULL,*vertical=root; TreeLinkNode* head=root,*cur=NULL,*pre=NULL; while(head){ cur=head; pre=NULL; head=NULL; while(cur){ if(cur->left){ if(!pre){ head=cur->left; pre=head; }else{ pre->next=cur->left; pre=pre->next; } } if(cur->right){ if(!pre){ head=cur->right; pre=head; }else{ pre->next=cur->right; pre=pre->next; } } cur=cur->next; } } }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 长海县| 内江市| 宁夏| 中山市| 株洲市| 类乌齐县| 临泽县| 五常市| 塔河县| 德州市| 普陀区| 利辛县| 潍坊市| 大同县| 扎鲁特旗| 南京市| 田阳县| 自治县| 天门市| 连山| 桐乡市| 麟游县| 定结县| 西青区| 察哈| 寿阳县| 日照市| 瓮安县| 蓝山县| 黎川县| 长春市| 富锦市| 腾冲县| 吴忠市| 横山县| 湘乡市| 湛江市| 荔浦县| 南漳县| 河南省| 克什克腾旗|