您的位置:首页 > 编程语言 > C语言/C++

leetcode 107. Binary Tree Level Order Traversal II(BFS)(Java和C++)

2017-12-14 18:33 459 查看
问题描述:

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).



思路:

利用广度优先搜索

Java代码:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public List<List<Integer>> levelOrderBottom(TreeNode root){
List<List<Integer>> result = new ArrayList<>();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<>();

4000
int num = queue.size();
for(int i = 0; i < num; i++){
TreeNode n = queue.poll();
if(n.left != null) queue.add(n.left);
if(n.right != null) queue.add(n.right);
list.add(n.val);
}
result.add(list);
}
Collections.reverse(result);
return result;
}

public static void main(String[] args) {
RomanToInt a=new RomanToInt();
//int[] at = {1,2,2,3,1};
String at = "abcdefg";
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(a.levelOrderBottom(root));
}


C++代码:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;

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 == NULL) return result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
int n = q.size();
vector<int> v;
for (int i = 0; i < n; i++) {
TreeNode* n = q.front();
q.pop();
if (n->left != NULL) q.push(n->left);
if (n->right != NULL) q.push(n->right);
v.push_back(n->val);
}
result.push_back(v);
}
reverse(result.begin(), result.end());
return result;
}
};

int main()
{
TreeNode *root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
Solution a;
vector<vector<int>> result = a.levelOrderBottom(root);
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j]<<" ";
}
cout << endl;
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: