leetcode117——Populating Next Right Pointers in Each Node II

Title effect: the next node pointer is filled right binary tree each node

Analysis: Similar to 116, but because it is not perfect binary tree, so the situation should be considered more.

Case 1: The first consideration is no longer simply leftmost pointer points to the first left-most layer of n nodes, but points to the first layer of n + 1 team head node father. So from the leftmost traversing the n-layer is consistent with the meaning of the questions.

Case 2: no longer connected to node 116 as two, but directly maintain the current node to be filled.

Code:

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
    Node* connect(Node* root) {
        Node *leftmost = root;
        while(leftmost != NULL){
            // 获取leftmost
            // 不一定是该层最左,因为leftmost实指下一层的队首元素的父节点
            // 从leftmost开始遍历,连接它的下一层节点
            while(leftmost && leftmost->left == NULL && leftmost->right == NULL)
                leftmost = leftmost->next;
            if(leftmost == NULL) break;
            Node *cur = NULL; //维护当前遍历到的节点,目的是填充cur->next
            // 遍历队列
            for(Node *head = leftmost;head != NULL;head = head->next){
                if(head->left){
                    if(cur != NULL){
                        cur->next = head->left;
                    }
                    cur = head->left;
                }
                if(head -> right){
                    if(cur != NULL){
                        cur->next = head->right;
                    }
                    cur = head->right;
                }
            }
            // 获取下一层最左节点
            leftmost = leftmost->left ? leftmost->left : leftmost->right;
        }
        return root;
    }
};

 

Published 295 original articles · won praise 4 · views 20000 +

Guess you like

Origin blog.csdn.net/tzyshiwolaogongya/article/details/104276769