zoukankan      html  css  js  c++  java
  • 117 Populating Next Right Pointers in Each Node II 每个节点的右向指针 II

    这是“每个节点的右向指针”问题的进阶。
    如果给定的树可以是任何二叉树,该怎么办?你以前的解决方案仍然有效吗?
    注意:
        你只能使用恒定的空间。
    例如,
    给定以下二叉树,
             1
           / 
          2    3
         /    
        4   5    7
    调用你的函数后,树应该看起来像这样:
             1 -> NULL
           / 
          2 -> 3 -> NULL
         /    
        4-> 5 -> 7 -> NULL

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

    Java实现:

    /**
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null){
                return;
            }
            LinkedList<TreeLinkNode> que=new LinkedList<TreeLinkNode>();
            que.offer(root);
            while(!que.isEmpty()){
                //记录本层节点的个数
                int size=que.size();
                for(int i=0;i<size;++i){
                    TreeLinkNode cur=que.poll();
                    //最后一个节点的next是null,不做处理
                    if(i<size-1){
                        TreeLinkNode next=que.peek();
                        cur.next=next;
                    }
                    if(cur.left!=null){
                        que.offer(cur.left);
                    }
                    if(cur.right!=null){
                        que.offer(cur.right);
                    }
                }
            }
        }
    }
    

    参考:https://segmentfault.com/a/1190000003465911

  • 相关阅读:
    centos7 查看启动ntp服务命令
    集群重启某一主机下所有osd down解决办法
    不卸载ceph重新获取一个干净的集群环境
    centos7 中文乱码解决方法
    ceph-deploy mon add 失败
    批量删除osd的shell脚本
    搭建自己的框架WedeNet(二)
    搭建自己的框架WedeNet(一)
    多线程总结
    C#中操作单个cookie和cookie字典
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8721752.html
Copyright © 2011-2022 走看看