zoukankan      html  css  js  c++  java
  • 【leetcode】Binary Tree Level Order Traversal I & II

    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即可

    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            queue<TreeNode*> Q;
            vector<vector<int>> ans;
            Q.push(root);
            while(!Q.empty())
            {
                int e = Q.size(); //当前层的结束位置
                vector<int> partans;
                for(int i = 0; i < e; i++)
                {
                    TreeNode * p = Q.front();
                    Q.pop();
                    if(NULL != p)
                    {
                        partans.push_back(p->val);
                        Q.push(p->left);
                        Q.push(p->right);
                    }
                }
                if(!partans.empty())
                    ans.push_back(partans);
            }
            return ans;
        }
    };

    网上DFS的代码:

    class Solution {
    protected:
        vector<vector<int>> ans;
        void dfs(TreeNode *root, int height){
            if (root == NULL) 
                return;
            while (ans.size() <= height)
                ans.push_back(vector<int>());
            ans[height].push_back(root->val);
            dfs(root->left, height + 1);
            dfs(root->right, height + 1);
        }
    
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
           dfs(root, 0);
            return ans;    
        }
    };

    Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

    [
      [15,7],
      [9,20],
      [3]
    ]

    跟上面只是顺序变了,加个reverse就行了。

  • 相关阅读:
    解决GIT可视化工具Sourcetree拉取失败问题
    记录常用Git命令
    vue开发移动端使用rem的适配方案
    使用HBuilderX实现打包vue项目成app
    使用vue+webpack从零搭建项目
    整理最近面试问道的问题
    模块化之seaJs学习和使用
    理解Object.defineProperty的作用
    vue生命周期
    使用gulp编译sass
  • 原文地址:https://www.cnblogs.com/dplearning/p/4627247.html
Copyright © 2011-2022 走看看