Shu-How Zの小窝

Loading...

199.二叉树的右视图

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function (root) {
  if (!root) return [];
  let dethMap = new Map(); //Map夺储,key是当国节点的高度,value是我们当前节点的信;
  let queue = [[root, 0]];
  while (queue.length) {
    //取出队首元素
    var [{ val, left, right }, depth] = queue.shift();
    //更新 MAP里面的每一个 key对应的一个val
    dethMap.set(depth, val);
    // 根据中序遍历的顺序,右节点先出队列 相同高度 map就替换了 只显示右节点
    depth++;
    if (left) {
      queue.push([left, depth]);
    }
    if (right) {
      queue.push([right, depth]);
    }
  }
  return [...dethMap.values()];
};
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}
let root = new TreeNode(2, new TreeNode(1), new TreeNode(3));
console.log(rightSideView(root));

posted @ 2024-12-07 21:31  KooTeam  阅读(11)  评论(0)    收藏  举报