国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 海口市| 海丰县| 泾阳县| 万荣县| 阿瓦提县| 龙江县| 商洛市| 洪洞县| 安陆市| 仙桃市| 永昌县| 蓬安县| 资源县| 郯城县| 承德市| 蒙城县| 乌苏市| 长乐市| 安平县| 上思县| 且末县| 新郑市| 蒲江县| 伊川县| 永春县| 乐至县| 合山市| 湖北省| 金寨县| 峨山| 井陉县| 陇川县| 无为县| 石泉县| 股票| 韶山市| 黎平县| 千阳县| 漾濞| 永福县| 沁阳市|