두 갈래 나무 층계 반복 | 지그재그로 두 갈래 나무 인쇄

레이어별 인쇄


폭 우선 검색.
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector > Print(TreeNode* pRoot) {
            vector> ret;
            
            if (pRoot == NULL) {
                return ret;
            }
            
            queue q;
            q.push(pRoot);
            while (!q.empty()) {
                int len = q.size();
                vector tmp(len);
                for (int i = 0; i < len; ++i) {
                    TreeNode* cur = q.front(); q.pop();
                    tmp[i] = cur->val;
                    if (cur->left) q.push(cur->left);
                    if (cur->right) q.push(cur->right);
                }
                ret.push_back(tmp);
            }
            return ret;
        }
};

지그재그 인쇄


BFS를 수정합니다.
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector > Print(TreeNode* pRoot) {
        vector> ret;
        
        if (pRoot == NULL) {
            return ret;
        }
        
        vector q;
        q.push_back(pRoot);
        bool sign = true;  // sign true , 
        for (int i = 0; i < q.size(); ) {
            int start = i, end = q.size() - 1;
            vector tmp(end-start+1);
            int k = 0;
            for (int j = start; j <= end; ++j) {
                tmp[k++] = q[j]->val;
                if (q[j]->left) q.push_back(q[j]->left);
                if (q[j]->right) q.push_back(q[j]->right);
            }
            if (!sign) std::reverse(tmp.begin(), tmp.end());
            ret.push_back(tmp);
            i = end + 1;
            sign = !sign;
        }
        return ret;
    }
    
};

다음으로 전송:https://www.cnblogs.com/ilovezyg/p/7591027.html

좋은 웹페이지 즐겨찾기