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

  • 相关阅读:
    BigPipe学习研究
    JavaSript模块规范
    WebSocket
    图片链接转成base64
    3000多台式机组装经验分享
    android textview 自动换行 整齐排版
    android 获取所有SD卡目录
    android获取系统信息
    在电脑上用chrome浏览器调试android手机里的网页代码时,无法看到本地加载的js文件
    android 根据坐标返回触摸到的View
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8721752.html
Copyright © 2011-2022 走看看