[JAVA]LeetCode199 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.

For example:
Given the following binary tree,
1 <—
/ \
2 3 <—
\ \
5 4 <—
You should return [1, 3, 4].
题目的含义是:从右边看,我们能看到的节点有哪些,相当于几何中投影的概念。
解题思路:1)深度遍历,先记录右边节点的最大高度。只有大于最大高度的节点才能打印出来。(我们自己思维去判断的时候,应该更倾向这种逻辑)
2)层次遍历,将最右边的节点存入list表中。这种想法写程序更容易理解。
实现1)思路代码如下所示:

 public List<Integer> rightSideView(TreeNode root) {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        Stack<TreeNode> stack1=new Stack<TreeNode>();//存储所有的节点,用来计算节点所在的高度
        List<Integer> list=new ArrayList<Integer>();
        TreeNode current=root;
        int curHeight=1;
        int rightHeight=0;
        while(current!=null||!stack.isEmpty())
        {
            if(current!=null)
            {
            if(curHeight>rightHeight)
            {
                list.add(current.val);
            }
            stack.push(current);
            stack1.push(current);
            current=current.right;
            ++curHeight;
            }else
            {
               current=stack.pop();
               //计算当前current节点所在的height值
               while(!stack1.isEmpty())
               {
                   if(stack1.peek()==current)
                   {
                       curHeight=stack1.size();
           if(curHeight>rightHeight)rightHeight=curHeight;
                       break;
                   }
                   stack1.pop();
               }
               current=current.left;
               ++curHeight;
            }
        }
        return list;
    }

实现2)思路程序如下:

 public List<Integer> rightSideView(TreeNode root) {
       List<Integer> list=new ArrayList<Integer>();
       if(root==null)return list;
       Queue<TreeNode> queue=new LinkedList<TreeNode>();
       TreeNode current=root;
       queue.offer(current);
       queue.offer(null);//相当于用null来做每层节点的间隔符
       while(!queue.isEmpty())
       {
         current=queue.poll();
         if(current!=null)
         {
            if(queue.peek()==null)
            {
                list.add(current.val);
            }
            if(current.left!=null)queue.add(current.left);
           if(current.right!=null)queue.add(current.right);
         }else
         {
            if(queue.isEmpty())
            {
                break;
            }else
            {
                queue.add(null);
            }
         }
       }
       return list;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值