LeetCode Populating Next Right Pointers in Each Node II

来源:互联网 发布:编程算法基础pdf 编辑:程序博客网 时间:2024/04/28 01:09

Populating Next Right Pointers in Each Node II

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
Solution:

/** * 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:    TreeLinkNode* get_next(TreeLinkNode* root){        if(!root)            return NULL;        if(root->left)            return root->left;        if(root->right)            return root->right;        return get_next(root->next);    }    void connect(TreeLinkNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        TreeLinkNode* left=root;        while(left){            root=left;            while(root){                if(root->left&&root->right){                    root->left->next=root->right;                    root->right->next=get_next(root->next);                }                else if(root->left||root->right)                    get_next(root)->next=get_next(root->next);                root=root->next;            }            left=get_next(left);        }    }};