关闭

LeetCode199 打印树最右边的值

标签: leetcode层遍历
106人阅读 评论(0) 收藏 举报
分类:

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


由于刚实现了分层打印二叉树的功能,并且可以记录行号。那么实现上面这个功能就不难了。在分层打印二叉树的基础上,判断cur,last节点是否重合,重合就是最后一个元素了,打印出来就行了。


/**
 * Created by kyle on 2016/5/31.
 */
public class RIghtSideTree {

  static   public List<Integer> rightSideView(TreeNode root) {
        if(root == null){
            return  new ArrayList<Integer>();
        }
        TreeNode currentTreeNode = new TreeNode(0);
        List<Integer> list = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int cur =0, last =1;
        while(queue.size() != 0){
            while(cur < last){
                currentTreeNode = queue.remove();
                if(currentTreeNode.left != null){
                    queue.add(currentTreeNode.left);
                }
                if(currentTreeNode.right != null){
                    queue.add(currentTreeNode.right);
                }
                cur++;
            }
            list.add(currentTreeNode.val);

            cur =0;
            last = queue.size();
        }
        return  list;
    }

    static  TreeNode insertTree(TreeNode root, int val){
        if(root == null){
            root = new TreeNode(val);
            return root;
        }

        if(root.val >val){
            if(root.left == null){
                root.left = new TreeNode(val);
            }else {
                insertTree(root.left, val);
            }
        }else{
                if(root.right == null){
                    root.right = new TreeNode(val);
                }else {
                    insertTree(root.right, val);
                }

        }
        return  root;
    }

   static void showTree(TreeNode root){
        if(root == null){
           // System.out.println("[]");
            return;
        }

        showTree(root.left);
       System.out.println(root.val);
        showTree(root.right);
    }
    static  public  void main(String[] args){
        TreeNode tr;
        tr = null;
        tr = insertTree(tr, 18);
        tr = insertTree(tr, 5);
        tr = insertTree(tr, 2);
        tr = insertTree(tr, 8);
        tr = insertTree(tr, 81);
        tr = insertTree(tr, 101);
        System.out.println("Original:\n");
        showTree(tr);
       List<Integer> list = rightSideView(tr);
        System.out.println("side way");
        System.out.println(list);
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:41717次
    • 积分:1622
    • 等级:
    • 排名:千里之外
    • 原创:125篇
    • 转载:0篇
    • 译文:0篇
    • 评论:24条
    最新评论