populating-next-right-pointers-in-each-node(i,ii)

来源:互联网 发布:mac apktool使用教程 编辑:程序博客网 时间:2024/06/07 03:28

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

第一问:给出的二叉树是完全二叉树
代码如下:

/** * 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 *p=root,*q;        while(p->left)//注意这句话        {            q=p;            while(q)            {                q->left->next=q->right;                if(q->next)                {                    q->right->next=q->next->left;                }                q=q->next;            }            p=p->left;        }    }};

第二问:给出的二叉树是任意二叉树
代码如下:

/** * 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) {        while(root){            TreeLinkNode lqq(-1),*pre=&lqq;            while(root){                if(root->left)                 {                    pre->next=root->left;                    pre=pre->next;                }                if(root->right)                 {                    pre->next=root->right;                    pre=pre->next;                }                root=root->next;            }            root=lqq.next;        }    }};
阅读全文
0 0
原创粉丝点击