题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
- 谷歌(Google)
- 亚马逊(Amazon)
- 微软(Microsoft)
- 苹果(Apple)
- 华为
- 彭博(Bloomberg)
- 甲骨文(Oracle)
- Servicenow
AC 代码
- Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
// 解决方案(1)
class Solution {
private List<List<Integer>> list;
private Queue<TreeNode> queue;
private Map<TreeNode, Integer> map;
public List<List<Integer>> levelOrder(TreeNode root) {
list = new ArrayList<>();
if (null == root) {
return list;
}
map = new HashMap<TreeNode, Integer>(){{put(root, 0);}};
queue = new LinkedList<TreeNode>(){{offer(root);}};
dfs(root, 0);
bfs();
return list;
}
private void bfs() {
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
Integer index = map.get(node);
if (list.size() <= index) {
list.add(new ArrayList<>());
}
list.get(index).add(node.val);
if (null != node.left) {
queue.offer(node.left);
}
if (null != node.right) {
queue.offer(node.right);
}
}
}
private void dfs(TreeNode node, int index) {
map.put(node, index);
if (null != node.left) {
dfs(node.left, index + 1);
}
if (null != node.right) {
dfs(node.right, index + 1);
}
}
}
// 解决方案(2)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if(root != null) queue.add(root);
while(!queue.isEmpty()) {
List<Integer> tmp = new ArrayList<>();
for(int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
tmp.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
res.add(tmp);
}
return res;
}
}
- C++
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> res;
int cnt = 0;
if(root != NULL) que.push(root);
while(!que.empty()) {
vector<int> tmp;
for(int i = que.size(); i > 0; --i) {
root = que.front();
que.pop();
tmp.push_back(root->val);
if(root->left != NULL) que.push(root->left);
if(root->right != NULL) que.push(root->right);
}
res.push_back(tmp);
}
return res;
}
};