博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Binary Tree Level Order Traversal II
阅读量:4478 次
发布时间:2019-06-08

本文共 2171 字,大约阅读时间需要 7 分钟。

题目描述:()

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? 

解题思路

递归版:

/** * 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
> levelOrderBottom(TreeNode* root) { travel(root, 1); reverse(result.begin(), result.end()); return result; } void travel(TreeNode *root, int level) { if (!root) return; if (level > result.size()) { result.push_back(vector
()); } result[level - 1].push_back(root->val); travel(root->left, level + 1); travel(root->right, level + 1); }private: vector
> result;};

迭代版:

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     vector
> levelOrderBottom(TreeNode* root) {13 vector
> result;14 if (!root) return result;15 16 queue
current, next;17 vector
level;18 current.push(root);19 20 while (!current.empty()) {21 while (!current.empty()) {22 TreeNode *tmp = current.front();23 current.pop();24 level.push_back(tmp->val);25 26 if (tmp->left != nullptr) next.push(tmp->left);27 if (tmp->right != nullptr) next.push(tmp->right);28 }29 30 result.push_back(level);31 level.clear();32 swap(current, next);33 }34 35 reverse(result.begin(), result.end());36 37 return result;38 }39 };

 

转载于:https://www.cnblogs.com/skycore/p/5004734.html

你可能感兴趣的文章
C# 安装包制作
查看>>
【P2564】生日礼物(单调队列)
查看>>
Instuments工具
查看>>
新创建django项目,但网页打不开127.0.0.1:8000
查看>>
Python练习-内置函数的应用
查看>>
洛谷P3905 道路重建
查看>>
数据表格 - DataGrid - 行编辑
查看>>
HQL查询语句
查看>>
jsp听课笔记(四)
查看>>
vim
查看>>
数组的键/值操作函数
查看>>
Android单点触控与多点触控切换的问题解决方案
查看>>
JS常用函数与方法
查看>>
十、Shell基础
查看>>
py16 面向对象深入
查看>>
CentOS 7 安装 Gitlab
查看>>
JavaScript-03-常见函数
查看>>
ajax 设置Access-Control-Allow-Origin实现跨域访问
查看>>
去掉ExpandableListView的箭头图标
查看>>
[LeetCode]Binary Tree Level Order Traversal II
查看>>