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

    题目:Follow up for problem "Populating Next Right Pointers in Each Node".

    What if the given tree could be any binary tree? Would your previous solution still work?

    Note:

    • You may only use constant extra space.

    For example,

    Given the following binary tree,

             1
           /  
          2    3
         /     
        4   5    7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  
          2 -> 3 -> NULL
         /     
        4-> 5 -> 7 -> NULL


    思路:

    这一题的思路更为巧妙,我觉得现在尤其注意一点 ,在链表开头加上一个空链表是一个非常好的方法。

    对于本题,我似乎忽视的一点就是,对于当前层次的节点,是默认为右边是链接好的,而之前的一个类似题目,是判断当前节点的next 的了的。这个是区别。

    具体思路是:在每一层之前加上一个dummy ,如果当前节点存在左孩子,dummy 指向左孩子,存在右孩子,tail 首先指向 下一个,再指向右孩子。直到当前节点为空。

    接下来就是之前的dummy 设为当前节点,如此循环反复。

    代码:

    /**
     * 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) {
            TreeLinkNode *dummy=new TreeLinkNode(0);
            
            if(root==NULL)  return;
            
            while(root!=NULL){
                TreeLinkNode *tail=dummy;
                while(root!=NULL){
                    if(root->left){
                        tail->next=root->left;
                        tail=tail->next;
                    }
                    if(root->right){
                        tail->next=root->right;
                        tail=tail->next;
                    }
                    root=root->next;
                }
                root=dummy->next;
                dummy->next=NULL;//如果没有这句话,那么dummy只是上面那一层的
            }
            delete dummy;
        }
    };


  • 相关阅读:
    docker容器网络查看
    资源模型、资源管理
    kubectl命令设置在元集群上
    K8S容器网络
    Kubernetes部署Prometheus+Grafana以及HPA实验测试
    Shell 脚本之 MySQL 一键安装及基本配置(几分钟搞定)
    安装 Flannel 报错:network plugin is not ready: cni config uninitialized
    uniapp h5页面引入企业微信js-sdk
    判断IP地址及闰年,并写出相关测试用例
    第一个自动化测试案例 java+selenium
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519853.html
Copyright © 2011-2022 走看看