【动画图解算法】从上到小打印二叉树
题目
思路
一.解题思路:
-
判空 -
新建一个集合data用来存储节点值,新建一个队列queue用来存储每一层的结果,将root存入队列 -
bfs方法循环遍历队列queue,直到空结束,每次遍历从queue的队首取出一个节点,然后将其值存入data集合中,然后判断该节点是否有左右节点,有则插入队尾 -
循环结束,data中存储的即为需要的结果,然后将其顺序转换成数组返回即可 。
图解思路
动画
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) {
return new int[0];
}
Queue<TreeNode> queue = new LinkedList<>();
if(root.left != null ) queue.add(root.left);
if(root.right != null ) queue.add(root.right);
ArrayList<Integer> numberList = new ArrayList<>();
numberList.add(root.val);
while(!queue.isEmpty()) {
TreeNode tempNode = queue.poll();
numberList.add(tempNode.val);
if(tempNode.left != null ) queue.add(tempNode.left);
if(tempNode.right != null ) queue.add(tempNode.right);
}
int[] array = new int[numberList.size()];
for (int i = 0;i < numberList.size(); i++) {
array[i] = numberList.get(i);
}
return array;
}
}
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<int> levelOrder(TreeNode* root) {
//先看是否为空树
if(root == nullptr)
return {};
vector<int> ans;
queue<TreeNode*> Bfs;
//将根节点加入队列
Bfs.push(root);
while(!Bfs.empty()){
TreeNode* temp = Bfs.front();
//开始广度优先搜索
ans.push_back(Bfs.front()->val);
Bfs.pop();
if(temp->left)
Bfs.push(temp->left);
if(temp->right)
Bfs.push(temp->right);
}
return ans;
}
};
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
if not root:
return []
tmp = collections.deque()
res = []
tmp.append(root)
while tmp:
node = tmp.popleft()
res.append(node.val)
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
return res
js
// ac地址:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
// 原文地址:https://xxoo521.com/2020-02-02-btree-level-travel/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var levelOrder = function(root) {
if (!root) {
return [];
}
const data = [];
const queue = [root];
while (queue.length) {
const first = queue.shift();
data.push(first.val);
first.left && queue.push(first.left);
first.right && queue.push(first.right);
}
return data;
};
Go
func levelOrder(root *TreeNode) (res []int) {
if root == nil{
return res
}
// 根节点入队
q := []*TreeNode{root}
var node *TreeNode
for i:=0;i < len(q);i++{
node = q[i]
res = append(res,node.Val)
if node.Left != nil{
q = append(q,node.Left)
}
if node.Right != nil{
q = append(q,node.Right)
}
}
return res
}