Leetcode 117. fill each node of the next right node pointer II and C ++ implementation solving ideas

Method a: layer preorder

Problem-solving ideas:

And 116 questions exactly the same, in fact, with queue queue simpler, without the order of shuffling back and forth. Queue.size using the length information queue (), may be able to do only one queue traversal sequence.

/*
// 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 == NULL) return root;
        //层序遍历
        stack<Node*> s1;
        s1.push(root);
        while(!s1.empty()){
            stack<Node*> s2;
            Node* temp1 = NULL;
            Node* temp2 = NULL;
            while(!s1.empty()){
                temp1 = s1.top();
                s1.pop();
                temp1->next = temp2;
                temp2 = temp1;
                if(temp1->right)
                    s2.push(temp1->right);
                if(temp1->left)
                    s2.push(temp1->left);
            }
            //s2中节点顺序是反过来的
            while(!s2.empty()){
                s1.push(s2.top());
                s2.pop();
            }
        }
        return root;
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/93410685