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

首頁 > 學院 > 開發設計 > 正文

Leetcode 117. Populating Next Right Pointers in Each Node II

2019-11-14 12:20:49
字體:
來源:轉載
供稿:網友

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. 由于不規則的樹結構,所以需要用pre,cur來找到新的連接關系的兩端;還需要一個head表示每層的起點。三個指針的interplay在代碼里面寫得很清楚。每次把head賦給cur,然后根據cur->left、cur->right是否存在來更新連接:如果cur->left存在,又看pre是否已經存在:不存在則這個節點就是head,且pre=cur->left;存在則就把這個節點作為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; } } }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凤城市| 略阳县| 达尔| 宝兴县| 凤庆县| 成武县| 潼南县| 大安市| 屯门区| 礼泉县| 和政县| 曲水县| 望谟县| 德阳市| 通辽市| 永州市| 菏泽市| 泾源县| 文山县| 隆化县| 昆明市| 文成县| 毕节市| 大冶市| 高雄县| 即墨市| 乐都县| 汉中市| 临高县| 新源县| 镇原县| 赫章县| 靖安县| 固镇县| 青浦区| 安乡县| 全椒县| 凤冈县| 北川| 丹寨县| 新竹市|