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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 117. Populating Next Right Pointers in Each Node II

2019-11-14 11:27:20
字體:
供稿:網(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來找到新的連接關(guān)系的兩端;還需要一個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; } } }};
上一篇:P1164 小A點菜

下一篇:Java enum的用法詳解

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 萨嘎县| 青浦区| 张北县| 辽阳市| 宝鸡市| 泊头市| 图们市| 海南省| 新邵县| 赫章县| 桂林市| 安仁县| 漳州市| 平顺县| 赤水市| 泰和县| 多伦县| 边坝县| 绩溪县| 余姚市| 都江堰市| 虎林市| 治县。| 巴马| 泸水县| 东阳市| 正宁县| 盖州市| 建昌县| 宜春市| 绥化市| 潍坊市| 开封市| 正阳县| 凤台县| 吴桥县| 淅川县| 鹤岗市| 西青区| 吴川市| 安新县|