LeetCode 116. Populating Next Right Pointers in Each Node

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 116. Populating Next Right Pointers in Each Node相关的知识,希望对你有一定的参考价值。

直接做的话用中序遍历做即可,但是要求空间复杂度O(1),所以不行

 

方法一:Recursive

和往常的递归写起来不太一样,这里一定要先将root的左右儿子连接起来,后面递归才能继续连接。如果不算递归所用栈的空间的话O(1)。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (root==NULL) return;
        if (root->left){ // if root has two sons
            root->left->next = root->right;
            if (root->next!=NULL){
                root->right->next = root->next->left;
            }
        }
        connect(root->left);
        connect(root->right);
    }
};

 

方法二:Non-recursive

每次连接下一层的node,通过next遍历这一层的所有节点(这样下一层的节点就都连接好了)。root = root->left 到下一层继续。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode *cur;
        while (root!=NULL){
            cur = root;
            while (cur!=NULL){
                if (cur->left!=NULL){
                    cur->left->next = cur->right;
                    if (cur->next){
                        cur->right->next = cur->next->left;
                    }
                }
                cur = cur->next;
            }
            root = root->left;
        }        
    }
};

 

以上是关于LeetCode 116. Populating Next Right Pointers in Each Node的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-116-Populating Next Right Pointers in Each Node

leetcode 116. Populating Next Right Pointers in Each Node

leetcode@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)

leetcode 116 Populating Next Right Pointers in Each Node ----- java

LeetCode OJ 116. Populating Next Right Pointers in Each Node

Leetcode 116. Populating next right pointers in each node I and II