117. 填充每个节点的下一个右侧节点指针 II

题目描述

Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your lastvious 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
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */

方法1

递归方法

class Solution {
public:
    Node * connect(Node *root) {

      if(root == nullptr)
        return nullptr;
      root->next = nullptr;
      connectCore(root);
      return root;      
    }

    void connectCore(Node*root)
    {
      //递归函数设计的层层递进
      if(root->left == nullptr && root->right == nullptr)
        return ;

      if(root->left!=nullptr && root->right!=nullptr)
        root->left->next = root->right;
      //需要外部解决next连接的子节点
      Node * theNode = nullptr;
      if(root->right!=nullptr)
        theNode = root->right;
      else
        theNode = root->left;

      if(root->next!=nullptr)
      {
        Node* cur = root->next;
        while(cur!=nullptr)
        {
          if(cur->left!=nullptr)
          {
            theNode->next = cur->left;
            break;
          }
          if(cur->right!=nullptr)
          {
            theNode->next = cur->right;
            break;
          }
          cur = cur->next;
        }
        if(cur == nullptr)
          theNode->next = nullptr;            
      }
      else
        theNode->next = nullptr;
      //这里调用时要注意要先连接最右边的
      if(root->right!=nullptr)
        connectCore(root->right);
      if(root->left!=nullptr)
        connectCore(root->left);

    }
};

方法2

一层一层,尾指针,虚拟的头节点

class Solution {
public:
    Node *connect(Node *root) {
        
      Node *first = root;
      while(first!=nullptr)
      {
        Node nextLevelHeadNode(-1);
        Node * last = & nextLevelHeadNode;
                                         
        for(auto p=first;p!=nullptr;p=p->next) 
        {
          if(p->left!=nullptr)
            {
              last->next = p->left;
              last = last->next;
            }
            if(p->right!=nullptr)
            {
              last->next = p->right;
              last = last->next;
            }

        }
        first = nextLevelHeadNode.next;
        nextLevelHeadNode.next = nullptr;
      }
      return root;
          
    }

};

posted on 2021-06-14 18:56  朴素贝叶斯  阅读(30)  评论(0编辑  收藏  举报

导航