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

    题目链接

    Problem description:

    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

    Accepted Code:
     1 /**
     2  * Definition for binary tree with next pointer.
     3  * struct TreeLinkNode {
     4  *  int val;
     5  *  TreeLinkNode *left, *right, *next;
     6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void connect_helper(TreeLinkNode *root) {
    12         if (root == NULL) return ;
    13         //  when root is a leaf node
    14         if (root->left == NULL && root->right == NULL) return;
    15         if (root->left != NULL && root->right != NULL)
    16             root->left->next = root->right;
    17         
    18         TreeLinkNode *p = NULL, *head = root; 
    19         // iterator on the level
    20         while (head->next != NULL && head->next->left == NULL && head->next->right == NULL)
    21             head = head->next;
    22         
    23         if (head->next != NULL) {
    24             if (head->next->left != NULL)
    25                 p = head->next->left;
    26             else
    27                 p = head->next->right;
    28         }
    29         // right child is not null
    30         if (root->right != NULL) 
    31             root->right->next = p;
    32         else 
    33             root->left->next = p;
    34         // recursive solve right and left child of root
    35         // attention that the right child should be proceeded first
    36         connect_helper(root->right);
    37         connect_helper(root->left);
    38     }
    39     void connect(TreeLinkNode *root) {
    40         // root = NULL
    41         if (root == NULL) return ;
    42         // deal root node
    43         root->next = NULL;
    44          
    45         connect_helper(root);
    46     } 
    47 };
    
    
    
    
    
    
    
  • 相关阅读:
    【转】Tomcat中部署java web应用程序
    【转】如何安装mysql服务
    【转】java_web开发入门
    【转】SVN 查看历史信息
    【转】java编译错误 程序包javax.servlet不存在javax.servlet.*
    【转】MySQL5安装的图解(mysql-5.0.27-win32.zip)
    【转】JAVA变量path , classpth ,java_home设设置作用和作用
    intellij idea 10.5介绍
    Java中的IO与NIO
    javaWeb完成注册功能
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3779987.html
Copyright © 2011-2022 走看看