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;
        }
    };
    
  • 相关阅读:
    iOS 之 创建分类
    iOS 之 动画
    iOS 倒出spa文件 打包
    js闭包
    wampserver配置多站点
    js重定向
    php obstart
    php保存远程图片
    php获取前天的昨天的日期
    weixin js接口
  • 原文地址:https://www.cnblogs.com/smallredness/p/10677106.html
Copyright © 2011-2022 走看看