Leetcode 117. 填充每个节点的下一个右侧节点指针 II 解题思路及C++实现

方法一:层序遍历

解题思路:

和第116题一模一样,其实,用队列queue更简单一些,不用将顺序倒来倒去。通过使用队列的长度信息queue.size(),可以只需要一个队列就能做到层序遍历。

/*
// 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;
    }
};

猜你喜欢

转载自blog.csdn.net/gjh13/article/details/93410685