0
点赞
收藏
分享

微信扫一扫

LeetCode: 116. Populating Next Right Pointers in Each Node


LeetCode: 116. 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

题目大意: 将给定的完全二叉树(所有的叶子节点在同一层,所有的父节点都有两个孩子),连接成上图的形式(要求空间复杂度为 O(1))。

解题思路 —— 递归求解, 分治思想

  • 给定的二叉树:
  • LeetCode: 116. Populating Next Right Pointers in Each Node_空间复杂度

  • 对左子树执行 ​​connect​​ 操作:
  • LeetCode: 116. Populating Next Right Pointers in Each Node_分治思想_02

  • 对右子树执行 ​​connect​​ 操作:
  • LeetCode: 116. Populating Next Right Pointers in Each Node_空间复杂度_03

  • 合并: 分别将左子树的每一层最右边的节点链接到右子树每一层的最左边节点:
    链接第二层:
  • LeetCode: 116. Populating Next Right Pointers in Each Node_空间复杂度_04

  • 链接第三层:
  • LeetCode: 116. Populating Next Right Pointers in Each Node_空间复杂度_05

AC 代码

/**
* 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) {
if(root == nullptr) return;

// 分别对左右子树操作
connect(root->left);
connect(root->right);

// 将左子树的每一层的最右边链接到右子树的最左边
TreeLinkNode* leftTreeRight = root->left;
TreeLinkNode* rightTreeLeft = root->right;
while(leftTreeRight != nullptr && rightTreeLeft != nullptr)
{
leftTreeRight->next = rightTreeLeft;
leftTreeRight = leftTreeRight->right;
rightTreeLeft = rightTreeLeft->left;
}
}
};


举报

相关推荐

0 条评论