当前位置:网站首页>Hierarchical output binary tree

Hierarchical output binary tree

2022-04-23 08:05:00 Pen drawing Acacia

var levelOrder = function(root) {
	if (!root) return [];
	let queue = [];
	let res = [];
	let level = 0;
	queue.push(root);
	let temp;
	while (queue.length) {
		res.push([]);
		let size = queue.length; //  Pay attention to the : 
		size--; // It is a very important skill in hierarchy traversal  
		while (size--) {
			//  Out of the team  
			let front = queue.shift();
			res[level].push(front.val); //  The team  
			if (front.left) queue.push(front.left);
			if (front.right) queue.push(front.right);
		}
		level++;
	}
	return res;
};


版权声明
本文为[Pen drawing Acacia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230624332609.html