zoukankan      html  css  js  c++  java
  • 【LeetCode】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,第二种基于DFS。

    代码:

    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>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if (!root) return res;
            queue<TreeNode*> q;
            vector<int> v;
            q.push(root);
            q.push(NULL);
            TreeNode *node;
            while(!q.empty()) {
                node = q.front();
                q.pop();
                if (node == NULL) {
                    res.push_back(v);
                    v.clear();
                    if (q.size()) q.push(NULL);
                } else {
                    v.push_back(node->val);
                    if (node->left) q.push(node->left);
                    if (node->right) q.push(node->right);
                }
            }
            return res;
        }
    };

     DFS:

    /**
     * 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) {
            search(root, 0);
            return res;
        }
    private:
        void search(TreeNode* node, int depth) {
            if (!node) return;
            if (res.size() == depth) {
                res.push_back(vector<int>());
            }
            
            res[depth].push_back(node->val);
            search(node->left, depth + 1);
            search(node->right, depth + 1);
        }
        vector<vector<int>> res;
    };
  • 相关阅读:
    IIS Post 大小超出允许的限制
    webpack从零开始第1课:安装webpack和webpack-dev-server
    React
    ubuntu 安装nodejs和git
    ubuntu 启用root用户方法
    ubuntu安装最新版node和npm
    MVC Dropdownlist数据绑定 默认值
    C#调用Excel VBA宏[转载]
    git download error processing
    mysqladmin 使用
  • 原文地址:https://www.cnblogs.com/jdneo/p/4787154.html
Copyright © 2011-2022 走看看