Binary Tree Level Order Traversal II
Posted xpp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Level Order Traversal II相关的知识,希望对你有一定的参考价值。
方法一:最简单的方式是traversal I 中的结果直接reverse就可以
/** * 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>> levelOrderBottom(TreeNode* root) { vector<vector<int>> result; if(root == nullptr) return result; stack<TreeNode *> s; s.push(root); while(!s.empty()) { vector<TreeNode *> tmp; vector<int> _result; while(!s.empty()) { tmp.push_back(s.top()); _result.push_back(s.top()->val); s.pop(); } result.push_back(_result); for(int i=tmp.size()-1; i>=0; --i) { if(tmp[i]->right != nullptr) s.push(tmp[i]->right); if(tmp[i]->left != nullptr) s.push(tmp[i]->left); } } reverse(result.begin(), result.end()); return result; } };
同样可以采用递归的方式
/** * 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>> levelOrderBottom(TreeNode* root) { vector<vector<int>> result; traverse(root, 1, result); reverse(result.begin(), result.end()); return result; } void traverse(TreeNode *root, int level, vector<vector<int> > &result) { if(root == nullptr) return; if(result.size() < level) result.push_back(vector<int>()); result[level-1].push_back(root->val); traverse(root->left, level+1, result); traverse(root->right, level+1, result); } };
方法二:这个题目除了可以使用栈数据结构,也可以使用队列数据结构
/** * 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>> levelOrderBottom(TreeNode* root) { vector<vector<int> > result; if(root == nullptr) return result; queue<TreeNode *> que; que.push(root); while(!que.empty()) { vector<TreeNode *> tmp; vector<int> _result; while(!que.empty()) { tmp.push_back(que.front()); _result.push_back(que.front()->val); que.pop(); } result.push_back(_result); for(int i=0; i<tmp.size(); ++i) { if(tmp[i]->left != nullptr) que.push(tmp[i]->left); if(tmp[i]->right != nullptr) que.push(tmp[i]->right); } } reverse(result.begin(), result.end()); return result; } };
以上是关于Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章
102. Binary Tree Level Order Traversal
LeetCode102. Binary Tree Level Order Traversal
Leetcode 103. Binary Tree Zigzag Level Order Traversal
#Leetcode# 103. Binary Tree Zigzag Level Order Traversal