199.Binary-Tree-Right-Side-View

199. Binary Tree Right Side View

题目地址

https://leetcode.com/problems/binary-tree-right-side-view/

题目描述

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

代码

Approach #1 Two Stacks + DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  public List<Integer> rightSideView(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    int max_depth = -1;

    Stack<TreeNode> nodeStack = new Stack<TreeNode>();
    Stack<Integer> depthStack = new Stack<Integer>();
    nodeStack.push(root);
    depthStack.push(0);

    while (!nodeStack.isEmpty()) {
      TreeNode node = nodeStack.pop();
      int depth = depthStack.pop();

      if (node != null) {
        max_depth = Math.max(max_depth, depth);

        if (!map.containsKey(depth)) {
          map.put(depth, node.val);
        }

        nodeStack.push(node.left);
        nodeStack.push(node.right); // 先弹出右节点
        depthStack.push(depth + 1);
        depthStack.push(depth + 1);
      }
    }

    List<Integer> rightView = new ArrayList<Integer>();
    for (int depth = 0; depth <= max_depth; depth++) {
      rightView.add(map.get(depth));
    }

    return rightView;
  }
}

Approach #2 Two Queues + BFS

class Solution {
  public List<Integer> rightSideView(TreeNode root) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    int max_depth = -1;

    Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
    Queue<Integer> depthQueue = new LinkedList<Integer>();
    nodeQueue.add(root);
    depthQueue.add(0);

    while (!nodeQueue.isEmpty()) {
      TreeNode node = nodeQueue.remove();
      int depth = depthQueue.remove();

      if (node != null) {
        max_depth = Math.max(max_depth, depth);

        map.put(depth, node.val);

        nodeQueue.add(node.left);
        nodeQueue.add(node.right);
        depthQueue.add(depth + 1);
        depthQueue.add(depth + 1);
      }
    }

   List<Integer> rightView = new ArrayList<Integer>();
    for (int depth = 0; depth <= max_depth; depth++) {
        rightView.add(map.get(depth));
    }

    return rightView;
  }
}

Last updated