LeetCode——111. Minimum Depth of Binary Tree

来源:互联网 发布:淘宝买dota2饰品 编辑:程序博客网 时间:2024/05/01 11:42

问题描述:

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).For example:Given binary tree [3,9,20,null,null,15,7], 3 / \9  20   / \  15  7return its level order traversal as:[  [15,7],  [9,20],  [3]]

  这道题大致的意思就是从下到上遍历二叉树,将每一层的节点存入一个list中,最后将每一层的list存入到一个总的list中。
  这道题实际上跟上一题几乎一模一样。
  Binary Tree Level Order Traversal

  从结果来看,这一题与上一题不同的地方就在最后结果的排列顺序,上一题是从上往下,这一题是从下往上,那么我们只要在将tempList插入到result时改变顺序,将它插入到result的头部,就可以实现逆序了。所以如果上一题做出来的话,这一题没有太大的问题。我就不细讲了。

直接上代码吧:

public List<List<Integer>> levelOrderBottom(TreeNode root) {        if(root == null)            return new LinkedList<List<Integer>>();        List<List<Integer>> result = new LinkedList<>();        Queue<TreeNode> tempQueue = new LinkedList<>();        tempQueue.offer(root);        while(tempQueue.peek() != null) {            List<Integer> tempList = new LinkedList<>();            int levelSize = tempQueue.size();            for(int i = 0; i < levelSize; i++) {                //弹出节点                TreeNode tempNode = tempQueue.poll();                tempList.add(tempNode.val);                //将他的左右节点添加进队列中                if(tempNode.left != null)                    tempQueue.offer(tempNode.left);                if(tempNode.right != null)                    tempQueue.offer(tempNode.right);            }            //其实这一题与上一题不同的地方就是结果list中的顺序相反            //那么我们在插入的时候改变顺序,从头部插入,就可以改变最终的顺序            result.add(0, tempList);        }        return result;}

  谢谢大家观看我的博客。如果有不明白的地方,或者是文中有错误的地方,欢迎指出,谢谢!

原创粉丝点击