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

题目描述

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.You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,Given the following perfect binary tree,

     1
   /  \
  2    3
 / \  / \
4  5  6  7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() {}

    Node(int _val, Node* _left, Node* _right, Node* _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

代码实现

class Solution {
public:
    Node *connect(Node *root) 
    {
      if(root == nullptr)
        return nullptr;
      root->next = nullptr;
      return connectCore(root);        
    }
    
    //树的遍历是完备的,只需要根据题意在遍历过程中
    //进行一些必要的操作,根据题意,观察到规律:左右子节点的next
    //都可以通过父节点的right指针和next指针而确定
    //一个根节点直接涉及到的节点是
    //左右子节点,也是我们递归下去传进去的参数,在
    //继续递归之前,需要把左右子节点next的连接确定好,也就是
    //说,递归函数传进去的参数的next是确定好了的
    Node* connectCore(Node*root)
    {                    
      //由于这里是完美二叉树,有左节点一定有右节点
      if(root->left!=nullptr)
      {
        root->left->next = root->right;
        if(root->next!=nullptr)
          root->right->next = root->next->left;
        else
          root->right->next = nullptr;
        //注意这里递归调用的顺序
        connectCore(root->left);
        connectCore(root->right);
      }
      return root;
    }
}; 

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

导航