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法
  • 相关阅读:
    vue router 跳转动画
    less 循环
    在iconfont上批量下载图标
    function(h)
    三元表达式
    CSS3 object-fit 属性
    MaC 修改MySQL密码
    CSS3 animation 属性
    css控制文字超过2行不显示
    ionic动画
  • 原文地址:https://www.cnblogs.com/zywscq/p/5221217.html
Copyright © 2011-2022 走看看