nianhua120的专栏

转载请注明csdn的地址,谢谢。

LeetCode199 打印树最右边的值

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);
    }
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nianhua120/article/details/51545694
文章标签: leetcode 层遍历
个人分类: 算法
上一篇自己练习的找第K大的数。
下一篇LeetCode162. Find Peak Element
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭