【leetcode】Populating Next Right Pointers in Each Node

来源:互联网 发布:小米6怎么样知乎 编辑:程序博客网 时间:2024/03/29 05:38

Populating Next Right Pointers in Each Node

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:
这里写图片描述

注意几个判断条件:

/** * Definition for binary tree with next pointer. * struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:    void connect(TreeLinkNode *root) {        if(root==NULL) return;        TreeLinkNode *current;        while(root->left!= NULL)        {            current=root;            while(current!= NULL)            {                current->left->next=current->right;                if(current->next!= NULL)                {                    current->right->next=current->next->left;                }                current=current->next;            }            root=root->left;        }    }};
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 dnf88级没任务了怎么办 0号柴油冻住了怎么办 不小心喝了生水怎么办 不小心吃了蟑螂怎么办 以租代购还不起怎么办 孩子被教官打了怎么办 三岁宝宝叛逆期怎么办 三岁宝宝很叛逆怎么办 孩子不听话怎么办有什么方法呢 打了三岁的宝宝怎么办 2岁半宝宝不听话怎么办 心里素质不好容易紧张怎么办 孩子二年级成绩差怎么办 遇到素质低的人怎么办 孩子上课注意力不集中怎么办 素质报告册丢了怎么办 潞城镇剩下5个村怎么办 高三复读生学籍怎么办 被检精子总数少怎么办 前向运动精子17%怎么办 精子形态正常率1怎么办 精子形态正常率2怎么办 精子头部畸形率高怎么办 椎底动脉供血不足怎么办 颈椎动脉供血不足怎么办 颈椎病引起头晕脑供血不足怎么办 淘宝店被释放了怎么办 被枣蝎子蛰了怎么办 六角螺丝拧花了怎么办 苹果螺丝滑丝了怎么办 六角螺帽拧花了怎么办 六角螺母拧花了怎么办 内六角螺丝滑丝怎么办 十字螺丝拧花了怎么办 梅花螺丝滑丝了怎么办 螺丝孔道滑丝了,怎么办 锅把铆钉松啦怎么办 膨胀螺丝孔大了怎么办 戒指不圆了怎么办妙招 眼镜框的腿断了怎么办 弹簧腿眼镜坏了怎么办