zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Populating Next Right Pointers in Each Node II **@

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

    接上一题目,输入的树不是perfect的。

    在这里深搜就不好使了。因为,在你往下深搜的时候,可能上一行的next还没处理到那里,所以会丢失信息。

    利用它的next结构,进行bfs,同时记录下一行的head节点。

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(root == NULL)
                return;
            
            TreeLinkNode *NextRowHead = NULL;
            TreeLinkNode *NextRowPrev = NULL;
            while(root)
            {
                if(root->left)
                {
                    if(NextRowHead == NULL) // the first element of next row
                    {
                        NextRowHead = root->left;
                    }
                    else
                        NextRowPrev->next = root->left; //它前面有点
                        
                    NextRowPrev = root->left;
                }
                if(root->right)
                {
                    if(NextRowHead == NULL)
                    {
                        NextRowHead = root->right;
                    }
                    else
                        NextRowPrev->next = root->right;
                        
                    NextRowPrev = root->right;
                }
                root = root->next;
                
                if(root == NULL) //begin a new row
                {
                    root = NextRowHead;
                    NextRowHead = NULL;
                    NextRowPrev = NULL;
                }
            }
        } 
    };
  • 相关阅读:
    LAMP搭建示例
    MySQL主从
    list多字段去重
    mysql按照某一个条件进行分组统计,同时又要保证一个相同字段的数据只统计一次
    sentinel自定义异常处理
    sentinel规则持久化
    zookeeper
    shiro
    iframe之间传递参数
    自定义标签
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3871249.html
Copyright © 2011-2022 走看看