Java實現二叉樹自底向上的層序遍歷
阿新 • • 發佈:2021-02-19
Java實現二叉樹自底向上的層序遍歷
例如,給定二叉樹 [3,9,20,null,null,15,7],
返回結果
二叉樹結構
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;
}
}
實現方法(層次遍歷)佇列
while(size>0)迴圈意思為將該層遍歷完,出佇列,裝入list中
private static List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> res = new LinkedList<>();
if (root == null)
return res;
TreeNode p = root;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(p);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> temp = new LinkedList<Integer>();
while (size > 0) {
p = queue.poll();
temp.add(p.val);
if (p.left != null) queue.offer(p.left);
if (p.right != null) queue.offer(p.right);
size--;
}
res.addFirst(temp);
}
return res;
}