LeetCode题目:Binary Tree Level Order Traversal

By | 2012 年 12 月 7 日

题目简单,经典方法。只不过这题需要每一个level单独作为一个vector输出,因此在每一个level结束的时候插入一个NULL标记。每当遇到这个标记,就说明一层已经完全访问了。



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]
]



代码:28ms过大集合

/**
 * 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 > levelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector > ret;
        if(NULL == root) return ret;
        queue trace;
        trace.push(root);
        trace.push(NULL);
        vector levelVals;
        while(true) {
            TreeNode *cur = trace.front();
            trace.pop();
            if(NULL == cur) {
                ret.push_back(levelVals);
                levelVals.erase(levelVals.begin(),levelVals.end());
                if(trace.size())
                    trace.push(NULL);
                else
                    break;
            } else {
                levelVals.push_back(cur->val);
                if(cur->left) trace.push(cur->left);
                if(cur->right) trace.push(cur->right);
            }
        }
        return ret;
    }
};



Code rewrite at 2012-12-22, 24ms pass the large test set

class Solution {
public:
    vector > levelOrder(TreeNode *root) {
        vector > ret;
        
        queue q;
        if(root) {
            q.push(root);
            q.push(NULL);
        }
        
        vector level;
        while(q.size()) {
            TreeNode *cur = q.front();
            q.pop();
            if(cur) {
                level.push_back(cur->val);
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            } else {
                ret.push_back(level);
                level.erase(level.begin(),level.end());
                if(q.size()) q.push(NULL);
            }
        }
        
        return ret;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注