Leetcode 103

Posted 村雨sup

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 103相关的知识,希望对你有一定的参考价值。

/**
 * 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) { stack<TreeNode*> st; vector<vector<int>> res; vector<int> first; if(root == NULL){ return res; } else{ first.push_back(root->val); res.push_back(first); } st.push(root); int flag = 0; while(!empty(st)){ vector<int> tres; queue<TreeNode*> que; while(!empty(st)){ TreeNode* temp = st.top(); que.push(temp); st.pop(); } if(flag%2 == 0){ while(!empty(que)){ TreeNode* temp = que.front(); if(temp->right != NULL){ st.push(temp->right); tres.push_back(temp->right->val); } if(temp->left != NULL){ st.push(temp->left); tres.push_back(temp->left->val); } que.pop(); } } if(flag%2 == 1){ while(!empty(que)){ TreeNode* temp = que.front(); if(temp->left != NULL){ st.push(temp->left); tres.push_back(temp->left->val); } if(temp->right != NULL){ st.push(temp->right); tres.push_back(temp->right->val); } que.pop(); } } flag++; if(tres.size()) res.push_back(tres); } return res; } };

上面是把stack转移到一个queue中

下面是利用两个stack互转做

/**
 * Definition for binary tree
 * 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;
        stack<TreeNode*> s1;
        stack<TreeNode*> s2;
        s1.push(root);
        vector<int> out;
        while (!s1.empty() || !s2.empty()) {
            while (!s1.empty()) {
                TreeNode *cur = s1.top();
                s1.pop();
                out.push_back(cur->val);
                if (cur->left) s2.push(cur->left);
                if (cur->right) s2.push(cur->right);
            } 
            if (!out.empty()) res.push_back(out);
            out.clear();
            while (!s2.empty()) {
                TreeNode *cur = s2.top();
                s2.pop();
                out.push_back(cur->val);
                if (cur->right) s1.push(cur->right);
                if (cur->left) s1.push(cur->left);
            }
            if (!out.empty()) res.push_back(out);
            out.clear();
        }
        return res;
    }
};

 



以上是关于Leetcode 103的主要内容,如果未能解决你的问题,请参考以下文章

p141 二叉树的 Z 字形遍历(leetcode 103)

LeetCode第103题—二叉树的锯齿形层序遍历—Python实现

leetcode103二叉树的锯齿形层序遍历

python-leetcode103-树的宽度遍历二叉树的锯齿形层次遍历

Leetcode 103

LeetCode ???103??? ?????????????????????????????????