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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

Leetcode 116. Populating Next Right Pointers in Each Node

2019-11-14 11:54:17
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Given a binary tree

struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next;}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

You may only use constant extra space. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). For example, Given the following perfect binary tree,

1 / / 2 3 / / / / 4 5 6 7

After calling your function, the tree should look like:

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

s思路: 1. 還是樹(shù)。變化是:除了縱向的遍歷樹(shù),現(xiàn)在還要增加功能,使其可以橫向遍歷。 2. 初略觀察有兩種pattern:一種是,2的next指向就是2的parent的child 3;另一種,5的next是5的parent的next 3的child。或者不一定這么看,問(wèn)題的另一面是:2的左孩子的next是2的右孩子;2的右孩子的next是2的next的左孩子。也是兩種情況,不同的是,一種從下往上看,所以每個(gè)node都借助parent;一種是從上往下看,所以每個(gè)node都借組child。由于是樹(shù),找孩子容易,找父母難。自然我們選擇用第二個(gè)思路,不過(guò)兩個(gè)思路都是一個(gè)思路的兩個(gè)角度。 3. 上面的思路也就意味著

//方法1: recursive.先處理root,然后左,最后右。in-orderclass Solution {public: void connect(TreeLinkNode *root) { // if(!root) return; if(!root->left&&!root->right) return; root->left->next=root->right; if(root->next) root->right->next=root->next->left; connect(root->left); connect(root->right); }};//方法2: iterative.不用queue,也不用stack.單用雙重循環(huán)就夠了,一個(gè)從上往下,一個(gè)從左往右class Solution {public: void connect(TreeLinkNode *root) { // TreeLinkNode* horizon=NULL,*vertical=root; while(vertical&&vertical->left){ horizon=vertical; while(horizon){ if(horizon->left) horizon->left->next=horizon->right; if(horizon->next) horizon->right->next=horizon->next->left; horizon=horizon->next; } vertical=vertical->left; } }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 彝良县| 石阡县| 红安县| 贵港市| 万宁市| 贵南县| 新营市| 平乡县| 蒲江县| 体育| 许昌市| 阿克苏市| 古浪县| 安福县| 星子县| 比如县| 民和| 庆阳市| 安泽县| 凌云县| 乐业县| 浦县| 田东县| 仙桃市| 枣庄市| 新营市| 淮安市| 游戏| 鄂温| 锡林郭勒盟| 庐江县| 多伦县| 宿州市| 青田县| 诏安县| 惠安县| 板桥市| 易门县| 涞水县| 宣恩县| 温宿县|