zoukankan      html  css  js  c++  java
  • 117.Populating Next Right Pointers in Each Node II

    class Solution {
    public:
        Node* connect(Node* root) {
            if (!root) return NULL;
            Node *p = root->next;
            while (p) {
                if (p->left) {
                    p = p->left;
                    break;
                }
                if (p->right) {
                    p = p->right;
                    break;
                }
                p = p->next;
            }
            if (root->right) root->right->next = p; 
            if (root->left) root->left->next = root->right ? root->right : p; 
            connect(root->right);
            connect(root->left);
            return root;
        }
    };
    
    // Non-recursion, more than constant space
    class Solution {
    public:
        Node* connect(Node* root) {
            if (!root) return NULL;
            queue<Node*> q;
            q.push(root);
            while (!q.empty()) {
                int len = q.size();
                for (int i = 0; i < len; ++i) {
                    Node *t = q.front(); q.pop();
                    if (i < len - 1) t->next = q.front();
                    if (t->left) q.push(t->left);
                    if (t->right) q.push(t->right);
                }
            }
            return root;
        }
    };
    
  • 相关阅读:
    SQLAlchemy Table(表)类方式
    MySQL简单入门
    第四次作业
    第三次随笔
    第二次随笔
    第一次随笔
    第四次随笔
    第三次作业
    第二次随笔
    第一次随笔
  • 原文地址:https://www.cnblogs.com/smallredness/p/10677106.html
Copyright © 2011-2022 走看看