116. Populating Next Right Pointers in Each Node

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

Follow up:

  • You may only use constant extra space.
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

Constraints:

  • The number of nodes in the given tree is less than 4096.
  • -1000 <= node.val <= 1000

算法思路:

最简单,也是最容易想到的就模拟levelOrder遍历过程,然后不断的加上next right pointer,实际上本题是一个完美二叉树,前序遍历,中序遍历,后续遍历理论上都可完成上述操作。

//模拟层序遍历过程加上next right pointer
//O(n) O(n)
class Solution {
public:
    Node* connect(Node* root) {
        if(root == NULL) return NULL;
        
        queue<Node*> que;
        que.push(root);
        Node* node = NULL;
        
        while(!que.empty()){
            int n = que.size();
            for(int i = 0; i < n; i++){
                if(i == 0){
                    node = que.front();
                    que.pop();
                }else{
                    node->next = que.front();
                    que.pop();
                    node = node->next;
                }
                if(node->left){
                    que.push(node->left);
                }
                if(node->right){
                    que.push(node->right);
                }
            }
        }
        
        return root;
    }
};

题目follow up中说使用O(1)空间复杂度,递归开销不计入空间开销,这就引导我们在模拟递归过程中加上next right pointer,考虑到是完美二叉树,这里模拟前序遍历过程加上next right pointer,代码非常简洁。

//O(n) O(1)
class Solution {
public:
    Node* connect(Node* root) {
        if(!root || !root->right) return root;
        
        root->left->next = root->right;
        if(root->next) root->right->next = root->next->left;
        
        connect(root->left);
        connect(root->right);
        
        return root;
    }
};

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值