zoukankan      html  css  js  c++  java
  • lintcode:二叉树的层次遍历

    地址:

    http://lintcode.com/zh-cn/problem/binary-tree-level-order-traversal/

    借助队列来完成

    class Solution {
    public:
        /*
         * @param root: A Tree
         * @return: Level order a list of lists of integer
         */
        vector<vector<int>> levelOrder(TreeNode * root) {
            // write your code here
            vector<vector<int>> res;
            if(root==NULL)
                return res;
            queue<TreeNode*> queue;
            queue.push(root);
            
            while(!queue.empty()){
                vector<int> cur;
                int len = queue.size();  
                
                while(len--){
                     TreeNode *tmp=queue.front();  
                     cur.push_back(tmp->val);
                     
                     queue.pop();
                     
                     if(tmp->left)
                        queue.push(tmp->left);
                    
                     if(tmp->right)
                        queue.push(tmp->right);
                     
                }
                res.push_back(cur);
            }
            return res;
        }
    };

    http://lintcode.com/zh-cn/problem/binary-tree-level-order-traversal-ii/

    给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

    这个题目是从底向上,其实类似上题,主要是因为用了vector方便很多:

    class Solution {
    public:
        /*
         * @param root: A tree
         * @return: buttom-up level order a list of lists of integer
         */
        vector<vector<int>> levelOrderBottom(TreeNode * root) {
            // write your code here
            queue<TreeNode*> queue;
            vector<vector<int>> res;
            int len;
            if(root==NULL)
                return res;
            queue.push(root);
    
            while(!queue.empty()){
                len = queue.size();
                vector<int> cur;
                while(len--){
                    TreeNode* temp = queue.front();
                    cur.push_back(temp->val);
                    queue.pop();
                    
                    if(temp->left){
                        queue.push(temp->left);
                    }
                    
                    if(temp->right){
                        queue.push(temp->right);
                    }
                }
                if(!cur.empty())
                res.insert(res.begin(),cur);
            }
            return res;
        }
    };
  • 相关阅读:
    WINREG.H 编译出错
    WINREG.H 编译出错
    JS创建对象的几种方式
    清除radio单选框外边距
    Dragging MovieClips
    Cannot Say No
    分层提高软件系统的可测试性
    如何从技术上掌控项目?
    领导我只需要你告诉我你要做什么,怎么做让我来好吗?
    如何依据框架进行任务分解
  • 原文地址:https://www.cnblogs.com/rimochiko/p/8440790.html
Copyright © 2011-2022 走看看