zoukankan      html  css  js  c++  java
  • [leetcode]117. Populating Next Right Pointers in Each NodeII用next填充同层相邻节点

    Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

    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指针

    设法将next指针指向同一层右侧相邻节点

    思路:

    递归,解法很巧妙。

    以 1 为curr,用pre来连接curr.left:2 和 curr.right:3。因为此时根节点 1的next指向null, 退出for循环
                1  ( curr )--->null 
                /  
    dummy(-1):pre--> 2---> 3
               /     
              4   5    7




    递归调用connect(dummy.next),因为dummy.next指向2此时 2 为curr。用pre来连接curr.left:4 和 curr.right:5。
                       1  
                   /        
                       2(curr)---> 3
                 /             
    dummy(-1):pre--> 4--->5 7

    继续走for循环, curr = curr.next, 此时curr为3。 继续用pre连接 curr.left(3的左子树为Null) 和 curr.right:7。

          1
                 /    
                       2 ---> 3(curr)
             /
    dummy(-1):pre--> 4--->5 --->7

    因为此时curr的next指向null, 退出for循环。
    继续递归调用connect(dummy.next)... 直至 root == null, return

    代码:

     1 public class Solution {
     2     public void connect(TreeLinkNode root) {
     3         if (root == null) return;
     4 
     5         TreeLinkNode dummy = new TreeLinkNode(-1);
     6         for (TreeLinkNode curr = root, prev = dummy;
     7                 curr != null; curr = curr.next) {
     8             if (curr.left != null){
     9                 prev.next = curr.left;
    10                 prev = prev.next;
    11             }
    12             if (curr.right != null){
    13                 prev.next = curr.right;
    14                 prev = prev.next;
    15             }
    16         }
    17         connect(dummy.next);
    18     }
    19 }
  • 相关阅读:
    如何自动生成参考文献格式
    VS2010+OpenCV 项目生成EXE文件如何在其他电脑上直接运行
    从多核CPU Cache一致性的应用到分布式系统一致性的概念迁移
    【译】为什么永远都不要使用MongoDB Why You Should Never Use MongoDB
    团队技能提升的二三事儿
    从微信朋友圈的评论可见性,谈因果一致性在分布式系统中的应用
    我所认为的软件可靠性的三重境界
    Redis核心原理与实践--事务实践与源码分析
    Redis核心原理与实践--Redis启动过程源码分析
    选择SaaS平台的那些事
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9124367.html
Copyright © 2011-2022 走看看