码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Binary Tree Level Order Traversal

时间:2014-12-01 14:13:05      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   sp   for   on   

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]
]
/**
 * 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) {
        vector<vector<int> > result;
        result.clear();
        if(root == NULL)
            return result;
        
        vector<TreeNode *> q[2];
        int current = 1;
        int next = 0;
        q[0].push_back(root);
        
        while(q[next].empty() == false)
        {
            current = !current;
            next = !next;
            vector<int> tempVec;
            for(auto w : q[current])
            {
                tempVec.push_back(w->val);
                if(w->left)
                {
                    q[next].push_back(w->left);
                }
                if(w->right)
                {
                    q[next].push_back(w->right);
                }
            }
            result.push_back(tempVec);
            tempVec.clear();
            q[current].clear();
        }
        
        
        
        return result;
    }
};

解题思路:层次遍历,在处理层次遍历的代码中,巧妙的运用2个向量保存当前正在处理的层的节点q[current],和该层节点的儿子所组成的下一层节点q[next]在处理开始将current和next互换,轻松实现层次切换。再有就是遍历向量的写法for(auto w :q[current])是c++11的新特性,在编译器中不用通过。

LeetCode Binary Tree Level Order Traversal

标签:des   style   blog   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/55open/p/4134884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!