本文主要是介绍32 - II. 从上到下打印二叉树 II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
comments: true
difficulty: 简单
edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9832%20-%20II.%20%E4%BB%8E%E4%B8%8A%E5%88%B0%E4%B8%8B%E6%89%93%E5%8D%B0%E4%BA%8C%E5%8F%89%E6%A0%91%20II/README.md
面试题 32 - II. 从上到下打印二叉树 II
题目描述
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3/ \9 20/ \15 7
返回其层次遍历结果:
[[3],[9,20],[15,7] ]
提示:
节点总数 <= 1000
注意:本题与主站 102 题相同:https://leetcode.cn/problems/binary-tree-level-order-traversal/
解法
方法一:BFS
我们可以使用 BFS 的方法来解决这道题。首先将根节点入队,然后不断地进行以下操作,直到队列为空:
- 遍历当前队列中的所有节点,将它们的值存储到一个临时数组 t t t 中,然后将它们的孩子节点入队。
- 将临时数组 t t t 存储到答案数组中。
最后返回答案数组即可。
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)。其中 n n n 是二叉树的节点个数。
Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution:def levelOrder(self, root: TreeNode) -> List[List[int]]:ans = []if root is None:return ansq = deque([root])while q:t = [] #保存单层节点for _ in range(len(q)):node = q.popleft()t.append(node.val)if node.left:q.append(node.left)if node.right:q.append(node.right)ans.append(t)return ans
Java
/*** 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;}Deque<TreeNode> q = new ArrayDeque<>();q.offer(root);while (!q.isEmpty()) {List<Integer> t = new ArrayList<>();for (int n = q.size(); n > 0; --n) {TreeNode node = q.poll();t.add(node.val);if (node.left != null) {q.offer(node.left);}if (node.right != null) {q.offer(node.right);}}ans.add(t);}return ans;}
}
C++
/*** 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>> levelOrder(TreeNode* root) {vector<vector<int>> ans;if (!root) return ans;queue<TreeNode*> q{{root}};while (!q.empty()) {vector<int> t;for (int n = q.size(); n; --n) {auto node = q.front();q.pop();t.push_back(node->val);if (node->left) q.push(node->left);if (node->right) q.push(node->right);}ans.push_back(t);}return ans;}
};
Go
/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/
func levelOrder(root *TreeNode) (ans [][]int) {if root == nil {return}q := []*TreeNode{root}for len(q) > 0 {t := []int{}for n := len(q); n > 0; n-- {node := q[0]q = q[1:]t = append(t, node.Val)if node.Left != nil {q = append(q, node.Left)}if node.Right != nil {q = append(q, node.Right)}}ans = append(ans, t)}return
}
TypeScript
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function levelOrder(root: TreeNode | null): number[][] {const res = [];if (root == null) {return res;}const queue = [root];while (queue.length !== 0) {const n = queue.length;const tmp = new Array(n);for (let i = 0; i < n; i++) {const { val, left, right } = queue.shift();tmp[i] = val;left && queue.push(left);right && queue.push(right);}res.push(tmp);}return res;
}
Rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {let mut res = Vec::new();if root.is_none() {return res;}let mut queue = VecDeque::new();queue.push_back(root);while !queue.is_empty() {let n = queue.len();let mut vals = Vec::with_capacity(n);for _ in 0..n {let mut node = queue.pop_front().unwrap();let mut node = node.as_mut().unwrap().borrow_mut();vals.push(node.val);if node.left.is_some() {queue.push_back(node.left.take());}if node.right.is_some() {queue.push_back(node.right.take());}}res.push(vals);}res}
}
JavaScript
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*/
/*** @param {TreeNode} root* @return {number[][]}*/
var levelOrder = function (root) {let ans = [];if (!root) {return ans;}let q = [root];while (q.length) {let t = [];for (let n = q.length; n; --n) {const { val, left, right } = q.shift();t.push(val);left && q.push(left);right && q.push(right);}ans.push(t);}return ans;
};
C#
/*** Definition for a binary tree node.* public class TreeNode {* public int val;* public TreeNode left;* public TreeNode right;* public TreeNode(int x) { val = x; }* }*/
public class Solution {public IList<IList<int>> LevelOrder(TreeNode root) {if (root == null) {return new List<IList<int>>();}Queue<TreeNode> q = new Queue<TreeNode>();q.Enqueue(root);List<IList<int>> ans = new List<IList<int>>();while (q.Count != 0) {List<int> tmp = new List<int>();int x = q.Count;for (int i = 0; i < x; i++) {TreeNode node = q.Dequeue();tmp.Add(node.val);if (node.left != null) {q.Enqueue(node.left);}if (node.right != null) {q.Enqueue(node.right);}}ans.Add(tmp);}return ans;}
}
这篇关于32 - II. 从上到下打印二叉树 II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!