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

    题目链接

    题目大意:与116题类似,区别是这题的二叉树是普通二叉树,而不是完全二叉树。要求空间复杂度o(1)。例子如下:

    法一:直接用116题的层序遍历的办法。代码如下(耗时5ms):

     1     public void connect(TreeLinkNode root) {
     2         if(root == null) {
     3             return;
     4         }
     5         Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
     6         q.offer(root);
     7         while(!q.isEmpty()) {
     8             //当前层一共有多少结点数
     9             int len = q.size();
    10             //遍历当前层的所有结点
    11             for(int i = 0; i < len; i++) {
    12                 TreeLinkNode tmp = q.poll();
    13                 //注意只计算到当前层倒数第二个结点即可。因为如果计算到最后一个的话,q中有值,会导致next出错。
    14                 if(i < len - 1) {
    15                     tmp.next = q.peek();
    16                 }
    17                 if(tmp.left != null) {
    18                     q.offer(tmp.left);
    19                 }
    20                 if(tmp.right != null) {
    21                     q.offer(tmp.right);
    22                 }
    23             }
    24         }
    25     }
    View Code

    法二:模仿116题的o(1)的解法,只是更灵活些,这里相当于直接给每一层形成了真正的一个单链表。具体代码如下(耗时1ms):

     1     public void connect(TreeLinkNode root) {
     2         TreeLinkNode nextLevel = new TreeLinkNode(0), cur = nextLevel;
     3         while(root != null) {
     4             if(root.left != null) {
     5                 //这里其实就是改变了pre.next,因为cur=pre,改变cur就是改变pre
     6                 cur.next = root.left;
     7                 cur = cur.next;
     8             }
     9             if(root.right != null) {
    10                 cur.next = root.right;
    11                 cur = cur.next;
    12             }
    13             root = root.next;
    14             //如果到了当前层结尾
    15             if(root == null) {
    16                 //重置cur
    17                 cur = nextLevel;
    18                 //重置root为下一层的第一个结点
    19                 root = nextLevel.next;
    20                 //重置nextLevel
    21                 nextLevel.next = null;
    22             }
    23         }
    24     }
    View Code
  • 相关阅读:
    request.getAttribute()和 request.getParameter()的区别
    jquery中$.get()提交和$.post()提交有区别吗?
    jQuery有几种选择器?
    jQuery 库中的 $() 是什么?
    JavaScript内置可用类型
    MySQL数据库中,常用的数据类型
    简单叙述一下MYSQL的优化
    什么是JDBC的最佳实践?
    Vue官网教程-条件渲染
    Vue官网教程-Class与Style绑定
  • 原文地址:https://www.cnblogs.com/cing/p/8953169.html
Copyright © 2011-2022 走看看