Binary Tree Level Order Traversal [LEETCODE]

weixin_34104341發表於2020-04-07

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? 


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 
====================================================================
 
Using two vector to perform a level order traverse.
/**
 * 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
        vector<vector<int> > result;
        if(NULL == root){
            return result;
        }
        vector<TreeNode *> v1;
        vector<TreeNode *> v2;
        vector<int> line;
        v1.push_back(root);
        while(!v1.empty()){
            line.clear();
            for (int i = 0; i < v1.size(); i++){
                line.push_back(v1[i]->val);
                if(v1[i]->left) v2.push_back(v1[i]->left);
                if(v1[i]->right) v2.push_back(v1[i]->right);
            }
            result.push_back(line);
            v1 = v2;
            v2.clear();
        }
            
        return result;        
    }
};

In first submission, I forggot to clear v2, encountered into a Memerory Exceeded Error. I fixed it with second submission.

轉載於:https://www.cnblogs.com/scenix/p/3343103.html

相關文章