LeetCode | Binary Tree Level Order Traversal

题目:

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路:

题目类似二叉树的宽度优先遍历,可以通过一个队列来实现。但是队列中的每个节点都需要增加一个数值表示层次(level)。由于我们只需要对相邻的层次进行区分,因此可以将层次简化成level%2,或bool值来表示。


代码:

/**
 * 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> > levelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        TreeNode * q1[10000];
        bool q2[10000];
        int begin=0;
        int end=0;
        
        if(root == NULL)
        {
            vector<vector<int> > v;
            return v;
        }
        else
        {
            vector<vector<int> > v;
            q1[end] = root;
            q2[end++] = true;
            
            bool level = true;
            
            vector<int> * tmp = new vector<int>();
            while(begin!=end)
            {
                TreeNode * p = q1[begin];
                bool cur = q2[begin++];
                
                if(cur != level)
                {
                    v.push_back(*tmp);
                    delete tmp;
                    tmp = new vector<int>();
                    level = !level;
                    
                }
                if(cur == level)
                {
                    if(p->left != NULL)
                    {
                        q1[end] = p->left;
                        q2[end++] = !cur;
                    }
                    if(p->right != NULL)
                    {
                        q1[end] = p->right;
                        q2[end++] = !cur;
                    }
                    tmp->push_back(p->val);
                }
                
            }
            v.push_back(*tmp);
            return v;
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11820189
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞