这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » binary-tree-level-order-traversal-ii

共1条 1/1 1 跳转至

binary-tree-level-order-traversal-ii

高工
2018-01-22 17:17:51     打赏

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


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


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".


思路:层次遍历二叉树,然后再进行逆序操作;


[cpp] view plain copy
  1. class Solution {  

  2. public:  

  3.     vector<vector<int>> levelOrderBottom(TreeNode* root)  

  4.     {  

  5.         vector<vector<int>> res;  

  6.   

  7.         if (root == NULL)  

  8.         {  

  9.             return res;  

  10.         }  

  11.   

  12.         queue<TreeNode*> q;  

  13.         q.push(root);  

  14.   

  15.         while (q.size()>0)  

  16.         {  

  17.             vector<int> level;  

  18.             for (int i = 0, n = q.size(); i<n; i++)  

  19.             {  

  20.                 TreeNode* tmp = q.front();  

  21.                 q.pop();  

  22.   

  23.                 level.push_back(tmp->val);  

  24.   

  25.                 if (tmp->left)  

  26.                 {  

  27.                     q.push(tmp->left);  

  28.                 }  

  29.                 if (tmp->right)  

  30.                 {  

  31.                     q.push(tmp->right);  

  32.                 }  

  33.             }  

  34.   

  35.             res.push_back(level);  

  36.         }  

  37.   

  38.         reverse(res.begin(), res.end());  

  39.   

  40.         return res;  

  41.     }  

  42. }; 




共1条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]