Binary Tree Right Side View

 Total Accepted: 8075 Total Submissions: 30533My Submissions

Question Solution 


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       <---


You should return [1, 3, 4].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

分析,直观上只需考虑最右边的元素,没有则考虑左儿子,但会出现以下状况

      1

    /  \

   2    3

  /

 4

我们的解决方案是,以层为单位,使用Queue类,只将每一层最右的节点放入结果list中


public class Solution {

    

    public List<Integer> rightSideView(TreeNode root) {

        List<Integer> x=new ArrayList<Integer>();

        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        if(root!=null)

        {    

            TreeNode z=null;

            TreeNode y=null;

            queue.add(root);

            queue.add(z);

            boolean o=false;

            while(queue.peek()!=null)

            {

                o=false;

                y=queue.element();

                x.add(y.val);

                while(y!=null)

                {

                    if(y.right!=null)

                    {

                        o=true;

                        queue.add(y.right);

                    }

                    if(y.left!=null)

                    {

                        o=true;

                        queue.add(y.left);

                    }

                    

                    queue.remove();

                    y=queue.element();

                }

                if(o==true)

                    queue.add(z);

                queue.remove();

            }

        }

        return x;

    }

}