Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字节&Leetcode 199. 二叉树的(左)右视图 #172

Open
mameikagou opened this issue Dec 13, 2024 · 1 comment
Open

字节&Leetcode 199. 二叉树的(左)右视图 #172

mameikagou opened this issue Dec 13, 2024 · 1 comment

Comments

@mameikagou
Copy link

题目链接:https://leetcode.cn/problems/binary-tree-right-side-view/description/
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

输入:root = [1,2,3,null,5,null,4]
输出:[1,3,4]
image

输入:root = [1,2,3,4,null,null,null,5]
输出:[1,3,4,5]
image

@mameikagou
Copy link
Author

mameikagou commented Dec 13, 2024

解答:左右视图就是层序遍历的每层的第一或者最后一个节点;

var rightSideView = function(root) {
    if(!root){
		return [];
	}
	let stack = [];
	let res = [];
	stack.push(root)
	while(stack.length>0){
		let len = stack.length;
		// 对每一层进行处理
		for(let i=0;i<len;i++){
			let cur = stack.shift()
			if(i===len-1){
				res.push(cur.val)
			}
			if(cur.left!==null){
				stack.push(cur.left)
			}
			if(cur.right!==null){
				stack.push(cur.right)
			}
		}
	}
	return res;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant