Binary Tree Right Side View 二叉树右视图

1.问题描述

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.

For example:
Given the following binary tree,

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

2.解题思路

这道题最容易理解的思路是使用层次遍历的方法去解。
层次遍历的时候,分层记录每一层的所有节点,然后输出该层最右边的节点即可。

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by wanglei on 19/4/14.
 */
public class BinaryTreeRightSide {

    public static TreeNode<Integer> init() {
        TreeNode<Integer> root = new TreeNode<>(1);
        TreeNode<Integer> node2 = new TreeNode<>(2);
        TreeNode<Integer> node3 = new TreeNode<>(3);
        TreeNode<Integer> node4 = new TreeNode<>(4);
        TreeNode<Integer> node5 = new TreeNode<>(5);
        root.left = node2;
        root.right = node3;
        node3.right = node4;
        node2.right = node5;
        return root;
    }

    public static void rightSide1(TreeNode<Integer> root) {
        Deque<TreeNode<Integer>> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root != null) {
            queue.offer(root);
        }
        while(queue.size() > 0) {
            int levelnum = queue.size();
            List<Integer> inner = new ArrayList<>();
            for(int i=0; i<levelnum; i++) {
                TreeNode<Integer> tmp = queue.poll();
                inner.add(tmp.data);
                if(tmp.left != null) {
                    queue.offer(tmp.left);
                }
                if(tmp.right != null) {
                    queue.offer(tmp.right);
                }
            }
            result.add(inner);
        }

        for(List<Integer> innerlist: result) {
            System.out.println(innerlist.get(innerlist.size() - 1));
        }
    }

    public static void main(String[] args) {
        TreeNode<Integer> root = init();
        rightSide1(root);
    }
}

输出结果为:

1
3
4
发布了425 篇原创文章 · 获赞 1607 · 访问量 436万+

猜你喜欢

转载自blog.csdn.net/bitcarmanlee/article/details/89302635