zoukankan      html  css  js  c++  java
  • leetcode 102 Binary Tree Level Order Traversal(DFS||BFS)

    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 a binary tree node.
     * 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) {
            if(root == NULL){
                vector<vector<int> >ans(0);
                return ans;
            }
            
            queue<pair<TreeNode*,int> >q;
            q.push(make_pair(root,0));
            
            vector<vector<int> >ans;
            
            while(!q.empty()){
                TreeNode* t=q.front().first;
                int depth=q.front().second;
                
                if(ans.size()==depth){
                    ans.push_back(vector<int>());
                }
                
                ans[depth].push_back(t->val);
                
                if(t->left!=NULL){
                    q.push(make_pair(t->left,depth+1));
                }
                if(t->right!=NULL){
                    q.push(make_pair(t->right,depth+1));
                }
                q.pop();
            }
            
            return ans;
            
        }
    };
    BFS法
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int> >ans;
    
        void dfs(TreeNode* r,int depth){
            if(r==NULL) return ;
            
            if(ans.size()==depth){
                ans.push_back(vector<int>());
            }
            ans[depth].push_back(r->val);
            
            dfs(r->left,depth+1);
            dfs(r->right,depth+1);
        }
    
        vector<vector<int> > levelOrder(TreeNode* root) {
            dfs(root,0);
            return ans;
        }
            
    };
    DFS法
  • 相关阅读:
    游戏开发热门技术浅析
    SpringMVC文件分片上传,断点续传
    浏览器文件分片上传,断点续传
    网页文件分片上传,断点续传
    Web文件分片上传,断点续传
    JavaScript文件分片上传,断点续传
    js文件分片上传,断点续传
    html5文件分片上传,断点续传
    vue文件分片上传,断点续传
    csharp文件分片上传,断点续传
  • 原文地址:https://www.cnblogs.com/zywscq/p/5221217.html
Copyright © 2011-2022 走看看