LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
原题链接
中等
作者:
Ccc1Z
,
2020-07-15 20:01:41
,
所有人可见
,
阅读 471
思路:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root == null)
return ans;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
List<Integer> path = new ArrayList<>();
for(int i = 0 ; i < size ; i++){
TreeNode cur = que.poll();
path.add(cur.val);
if(cur.left != null)
que.offer(cur.left);
if(cur.right != null)
que.offer(cur.right);
}
ans.add(new ArrayList<>(path));
}
return ans;
}
}