js(76)~199. 二叉树的右视图

112 阅读1分钟

这道题我看题目,直接想到只要有有节点,就是push进数组,怎么执行都不对,想了都不会这么简单错误代码如下 image.png 看了题解才想到,还有一种如果右节点只有左节点,也算是右视图,也写二叉树两种常见思路,深度优先和广度优先

方法一 递归 深度优先

var rightSideView = function(root) {
	const res = [];
	let depth = 0;
	const r = node => {
			if(!node) return;
			depth ++;
			// 这一步就适用跟节点
			if (res.length < depth) {
				res.push(node.val);
			}
			r(node.right);
			r(node.left)
			// 这个--看不懂
			depth -- ;
	}
	r(root);
	return res;
};

方法二 广度优先 bfs

var rightSideView = function (root) {
	if (!root) return [];
	const s = [root];
	const res = []
	while (s.length) {
		// 当前层的数量
		let len = s.length;
		while (len--) {
			// 这儿 不能改成pop
			const n = s.shift();
			// 只放入最右边的
			if (!len) {
				res.push(n.val);
			}
			if (n.left) {
				s.push(n.left)
			}
			if (n.right) {
				s.push(n.right)
			}
		}
	}
	return res;

};