leetcode 199. 二叉树的右视图
问题描述: 给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]
示例 2:
输入: [1,null,3]
输出: [1,3]
思路: 用深度计算的方式遍历 一旦有了右节点 当前节点的左节点就没用了。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
function dfs(root,depth,res){
if(root==null)return false;
if(depth==res.length){
res.push(root.val)
}
depth++;
dfs(root.right,depth,res)
dfs(root.left,depth,res)
}
var rightSideView = function(root) {
// if(root==null)return [];
let res=[];
let depth=0;
dfs(root,depth,res);
return res;
};