[LeetCode] Populating Next Right Pointers in Each Node

 
       

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 to NULL.

Initially, all next pointers are set to NULL.

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,

         1

       /  \

      2    3

     / \  / \

    4  5  6  7

 

After calling your function, the tree should look like:

         1 -> NULL

       /  \

      2 -> 3 -> NULL

     / \  / \

    4->5->6->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) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

    if(root == NULL)

        return;

        

    TreeLinkNode *head = root, *last = root, *tmp_last = root;//store the horizontal list

    root -> next = NULL;

    

    //if head -> left == NULL, then this is the leaf level, end

    while(head -> left != NULL)

    {

        //list the head level node

        last = head -> left;//last stores the next level, which is what we want to connect

        last -> next = head -> right;//connect the right to the left

        last = head -> right;//last node switch to the right node of the head

        tmp_last = head;//head level last node

        while(tmp_last -> next != NULL)

        {

            tmp_last = tmp_last -> next;

            last -> next = tmp_last -> left;

            (tmp_last -> left) -> next = tmp_last -> right;

            last = tmp_last -> right;

        }

        

        last -> next = NULL;

        head = head -> left;

    } 

    }

};

 

你可能感兴趣的:(LeetCode)