[LeetCode]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

         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) {
        TreeLinkNode *ChildFrontNode = new TreeLinkNode (0);//子链表头节点
        TreeLinkNode *pre = ChildFrontNode;//记录先前值,方便生成链表
        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; // 根节点指向下一个
            if(root==NULL){
                root = ChildFrontNode->next;
                pre = ChildFrontNode;
                ChildFrontNode->next = NULL; //走到链表尾部,转到下一行ChildFrontNode
            }
        }
    }
};



你可能感兴趣的:([LeetCode]Populating Next Right Pointers in Each Node II)