Populating Next Right Pointers in Each Node II leetcode

来源:互联网 发布:淘宝店运营视频教程 编辑:程序博客网 时间:2024/05/01 08:24

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.

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
注意:不能只看root的一个next,有可能是多个next之后有左或者右孩子

class Solution {public:    void connect(TreeLinkNode *root) {        if(root == NULL)        return;        if(root->left != NULL && root->right != NULL) {            root->left->next = root->right;            TreeLinkNode* pNext = root->next;            while(pNext!=NULL && pNext->left == NULL && pNext->right == NULL) {                pNext = pNext->next;            }            if(pNext != NULL) {                root->right->next = pNext->left != NULL ? pNext->left:pNext->right;            }        } else if(root->left != NULL && root->right == NULL)  {            TreeLinkNode* pNext = root->next;
<span style="white-space:pre"></span>// 注意while循环条件            while(pNext!=NULL && pNext->left == NULL && pNext->right == NULL) {                pNext = pNext->next;            }            if(pNext != NULL) {                root->left->next = pNext->left != NULL ? pNext->left:pNext->right;            }                    } else if(root->left == NULL && root->right != NULL) {            TreeLinkNode* pNext = root->next;            while(pNext!=NULL && pNext->left == NULL && pNext->right == NULL) {                pNext = pNext->next;            }            if(pNext != NULL) {                root->right->next = pNext->left != NULL ? pNext->left:pNext->right;            }                   } else {            return;        }               connect(root->right);//必须先右再左        connect(root->left);    }};


0 0
原创粉丝点击