LeetCode | 117. Populating Next Right Pointers in Each Node II


题目:

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.
  • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

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

题意:

与116题的题意思路一致,不同的是输入的二叉树子树不是绝对平衡的,即有些节点包含左子树或右子树。代码是我第一版AC116题的源代码,思路一致。


代码:

void connect(TreeLinkNode *root) {
        if(root == NULL)
            return;
        queue<TreeLinkNode*> q;
        q.push(root);
        TreeLinkNode *cur, *pre = NULL;
        int cur_num = 1, next_num = 0;
        while(!q.empty())
        {
            cur = q.front();
            q.pop();
            cur_num--;            
            if(cur->left != NULL)
            {
                q.push(cur->left);
                next_num++;
            }
            if(cur->right != NULL)
            {
                q.push(cur->right);
                next_num++;
            }
            if(pre != NULL)
                pre->next = cur;
            pre = cur;
            if(cur_num == 0)
            {
                cur->next = NULL;
                pre = NULL;
                cur_num = next_num;
                next_num = 0;
            }
        }
        return;
    }

思路是广搜,记录每层的节点数,然后进行同层节点连接。











猜你喜欢

转载自blog.csdn.net/iLOVEJohnny/article/details/80666591