Add Sibling to Binary Tree

本文介绍了一种高效算法,用于填充二叉树节点中的nextRight指针,以便于快速访问同一层级的相邻节点。算法首先采用广度优先搜索(BFS)方式实现,随后提出了改进方案,利用父节点的nextRight指针访问子节点,最后简化为递归形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question:
Given a binary tree

struct Node {
Node* leftChild;
Node* rightChild;
Node* nextRight;
}
Populate the nextRight pointers in each node.

The first idea come out should be the BFS tree algorithm, which can traverse the binary tree layer by layer. We only need to connect the sibling for each layer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<pre>int populateNextRightBFS(Node* root) {
    if (!root)
        return 0;
    queue <Node*> q;
    q.push(root);
    int nextLayer = 0;
    int curLayer = 1;
    Node* prev = NULL;
    while (!queue.empty()) {
        Node* cur = queue.front();
        if (prev)
            prev->sibling = cur;
        if (cur->left) {
            queue.push(cur->left);
            nextLayer++;
        }
        if (cur->right) {
            queue.push(cur->right);
            nextLayer++;
        }
        queue.pop();
        curLayer--;
        prev = cur;
        if (!curLayer) {
            curLayer = nextLayer;
            nextLayer = 0;
            prev = NULL;
        }
    }
    return 0;
}

Above algorithm uses an queue, which can be saved actually. We could use the parent’s sibling to visit children’ siblings. Then we have the following algorithm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<pre>int populateNextRightExt(Node* root) {
    if (!root)
        return 0;
 
    if (root->left)
        root->left->sibling= root->right;
    Node* cur = root;
    if (root->right) {
        while (cur->sibling && !cur->sibling->left && !cur->sibling->right)
            cur = cur->sibling;
        if (cur->sibling && cur->sibling->left)
            root->right->sibling = cur->sibling->left;
        else if (cur->sibling && cur->sibling->right)
            root->right->sibling = cur->sibling->left;
        else
            root->right->sibling = NULL;
    }
 
    populateNextRight(root->right);
    populateNextRight(root->left);
 
    return 0;
}

P.S If the sibling only points to the node in one-step right, and NULL otherwise, we do not need to search for its sibling far away. The simplified algorithm is as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<pre>int populateNextRight(Node* root) {
    if (!root)
        return 0;
 
    if (root->left)
        root->left->sibling= root->right;
    if (root->right)
        root->right->sibling = (root->sibling) ? root->sibling->left : NULL;
 
    populateNextRight(root->right);
    populateNextRight(root->left);
 
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值