zoukankan      html  css  js  c++  java
  • [LeetCode]Binary Tree Level Order Traversal

    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]
    ]

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

     

    BFS,广度优先搜索。递归实现。迭代版需要用到队列。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void bfs(TreeNode* root,int level,vector<vector<int>>& result)
    13     {
    14         if(!root) return;
    15         if(level>result.size()) result.push_back(vector<int>());
    16         result[level-1].push_back(root->val);
    17         bfs(root->left,level+1,result);
    18         bfs(root->right,level+1,result);
    19     }
    20     vector<vector<int>> levelOrder(TreeNode* root) {
    21         vector<vector<int>> result;
    22         bfs(root,1,result);
    23         return result;
    24     }
    25 };
  • 相关阅读:
    bootstrap初识
    司徒正美居中方式
    css中的浮动(float)
    fio
    简易接口测试脚本
    字符加密
    Python 汉诺塔
    Python 找零问题
    Python 二分法
    Python 冒泡排序
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4807579.html
Copyright © 2011-2022 走看看