zoukankan      html  css  js  c++  java
  • leetcode_question_102 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]
    ]
    
    BFS:
    vector<vector<int> > levelOrder(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            vector<vector<int>> matrix;
            if(root == NULL) return matrix;
    		vector<int> r;
    		r.push_back(root->val);
    		matrix.push_back(r);
    
    		vector<TreeNode *> path;
    		path.push_back(root);
    		
    		int count = 1;
    		while(!path.empty())
    		{
    			TreeNode* tn = path.front();
    			if(tn->left) path.push_back(tn->left);
    			if(tn->right) path.push_back(tn->right);
    			path.erase(path.begin());
    			count--;
    			if(count==0)
    			{
    				vector<int> tmp;
    				vector<TreeNode*>::iterator it = path.begin();
    				for(;it != path.end(); ++it)
    					tmp.push_back((*it)->val);
                    if(tmp.size() > 0)
    				    matrix.push_back(tmp);
    				count = path.size();
    			}
    		}
    		return matrix;
        }


  • 相关阅读:
    ccr1
    与非CCR代码互操作
    ccr test
    CCR
    tpl + ccr
    TPL
    利用 Rational ClearCase ClearMake 构建高性能的企业级构建环境
    Android错误:Re-installation failed due to different application signatures
    C 单例模式
    C 工厂模式 还有其他的模式
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3333738.html
Copyright © 2011-2022 走看看