LeetCode 103. Binary Tree Zigzag Level Order Traversal

LeetCode 103. Binary Tree Zigzag Level Order Traversal

Solution1:基于层次遍历的微改

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (!root) return res;
        vector<int> temp;
        queue<TreeNode* > my_que; //队列用来暂时存储二叉树节点
        my_que.push(root);
        int cur = 1, next = 0, symbol = 0;
        while (!my_que.empty()) {
            temp.push_back(my_que.front()->val);
            cur--;
            if (my_que.front()->left) {
                my_que.push(my_que.front()->left);
                next++;
            }
            if (my_que.front()->right) {
                my_que.push(my_que.front()->right);
                next++;
            }
            my_que.pop();
            if (cur == 0) {
                if (symbol % 2 == 1) {
                    reverse(temp.begin(), temp.end());
                    res.push_back(temp);
                } else res.push_back(temp);
                temp.clear();
                cur = next;
                next = 0;
                symbol++;
            }
        }
        return res;
    }
};

Solution2:用两个栈来保存数据,时间复杂度为 O ( n )

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if(root == NULL)
            return res;
        vector<int> temp;
        stack<struct TreeNode* > stack_node[2];//栈数组,数组的每个元素均是栈,栈的数据类型是TreeNode*
        int cur = 0, next = 1;
        stack_node[cur].push(root);
        while(!stack_node[0].empty() || !stack_node[1].empty()) {
            temp.push_back(stack_node[cur].top()->val);
            if(cur == 0) {
                if(stack_node[cur].top()->left != NULL)
                    stack_node[next].push(stack_node[cur].top()->left);
                if(stack_node[cur].top()->right != NULL)
                    stack_node[next].push(stack_node[cur].top()->right);
            } else {
                if(stack_node[cur].top()->right != NULL)
                    stack_node[next].push(stack_node[cur].top()->right);
                if(stack_node[cur].top()->left != NULL)
                    stack_node[next].push(stack_node[cur].top()->left);
            }
            stack_node[cur].pop();
            if(stack_node[cur].empty()) {
                res.push_back(temp);
                temp.clear();
                cur = 1 - cur;
                next = 1 - next;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80743511
今日推荐