zoukankan      html  css  js  c++  java
  • [Leetcode] 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

    Solution:

    http://blog.csdn.net/wzy_1988/article/details/17412025

    这道题目首要是找到右孩子的第一个有效的next链接节点,然后再处理左孩子。然后依次递归处理右孩子,左孩子

     1 /**
     2  * Definition for binary tree with next pointer.
     3  * public class TreeLinkNode {
     4  *     int val;
     5  *     TreeLinkNode left, right, next;
     6  *     TreeLinkNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public void connect(TreeLinkNode root) {
    11         if (root == null)
    12             return;
    13         TreeLinkNode p = root.next;
    14         while (p != null) {
    15             if(p.left!=null){
    16                 p=p.left;
    17                 break;
    18             }
    19             if(p.right!=null){
    20                 p=p=p.right;
    21                 break;
    22             }
    23             p=p.next;
    24         }
    25         if (root.right != null) {
    26             root.right.next = p;
    27         }
    28         if (root.left != null) {
    29             root.left.next = (root.right == null) ? p : root.right;
    30         }
    31         connect(root.right);
    32         connect(root.left);
    33     }
    34 }
  • 相关阅读:
    数据结构总结——线段树
    [bzoj2131]免费的馅饼 树状数组优化dp
    [机房练习赛7.26] YYR字符串
    博客已搬家
    AFO
    COGS-2551 新型武器
    UVALive-3716 DNA Regions
    UVALive-4850 Installations
    UVALive-3983 Robotruck
    UVA-10859 Placing Lampposts
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4099542.html
Copyright © 2011-2022 走看看