4.31 leetcode -31populating-next-right-pointers-in-each-node

来源:互联网 发布:淘宝轮播代码超简单 编辑:程序博客网 时间:2024/06/06 05:32
题目描述

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 toNULL.
Initially, all next pointers are set toNULL.
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,


这个题目显然是一个分层遍历的应用,但是,分层遍历,会需要一个队列,而且和有关的,他这个需要常数空间。不过,说是,可以假定他是一个完美二叉树,再利用他已经存在的next

/** * 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) {        TreeLinkNode *proot = root;        TreeLinkNode *pstart = root;        TreeLinkNode *pnext = root;        if(root == NULL)            return;        proot->next = NULL;        if(root->left == NULL)            return;        pstart = root->left;        int flag = 0;//0 - right,1-left;        while(pstart !=NULL)            {            pnext = pstart;            flag = 0;            while(proot !=NULL)                {                if(flag == 0)                    {                    pnext->next = proot->right;                    proot = proot->next;                    flag = 1;                    pnext = pnext->next;                }                else                    {                    pnext->next = proot->left;                    flag = 0;                    pnext = pnext->next;                }            }            pnext->next = NULL;            proot = pstart;            pstart = pstart->left;        }    }};


阅读全文
0 0
原创粉丝点击