LeetCode_102 두 갈래 트리 층별 인쇄

1649 단어 LeetCode 문제
102. Binary Tree Level Order Traversal
Medium
169244FavoriteShare
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree  [3,9,20,null,null,15,7] ,

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

문제 해결 방법:
두 개의 대기열 순환 사용하기
문제 해결 코드:

/**
 * 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> levelOrder(TreeNode* root) {
        vector> res;
        if(root==nullptr)
            return res;
        TreeNode* p;
        queue mq;
        mq.push(root);
        while(!mq.empty())
        {
            queue temq;
            vector temRes;
            while(!mq.empty())
            {
                p=mq.front();
                mq.pop();   // 
                if(p->left)
                    temq.push(p->left);
                if(p->right)
                    temq.push(p->right);
                temRes.push_back(p->val);
            }
            res.push_back(temRes);
            mq=temq;
        }
        return res;
    }
};

 

좋은 웹페이지 즐겨찾기