zoukankan      html  css  js  c++  java
  • #Leetcode# 102. Binary Tree Level Order Traversal

    https://leetcode.com/problems/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,null,null,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) {
            vector<vector<int> > ans;
            if(!root) return ans;
            helper(root, ans, 1);
            return ans;
        }
        void helper(TreeNode* root, vector<vector<int> >& ans, int depth) {
            vector<int> v;
            if(depth > ans.size()) {
                ans.push_back(v);
                v.clear();
            }
            ans[depth - 1].push_back(root -> val);
            if(root -> left) 
                helper(root -> left, ans, depth + 1);
            if(root -> right)
                helper(root -> right, ans, depth + 1);
        }
    };
    

      

    很幸福的时间了

  • 相关阅读:
    装饰器
    FLASK
    Flask第一个实例
    各种各样的PyQt测试和例子
    项目实战:天气信息查询
    窗口设置、QSS
    槽和信号
    布局
    打印机
    菜单栏、工具栏、状态栏
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10133024.html
Copyright © 2011-2022 走看看