LeetCode-336 寻找二叉树的叶子节点

Input: [1,2,3,4,5]

          1

        / \

        2  3

      / \   

      4  5   

Output: [[4,5,3],[2],[1]]


/**

* Definition for a binary tree node.

* public class TreeNode {

*    int val;

*    TreeNode left;

*    TreeNode right;

*    TreeNode(int x) { val = x; }

* }

*/

classSolution{

public List<List<Integer>>findLeaves(TreeNode node){

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

         queue.add(node);

          Map<Integer,List<Integer>> map = new HashMap<>();

          int h = -1;

          while(!queue.isEmpty()){

              h++;

              System.out.println("h=="+h);

             int size = queue.size();

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

              for(int i=0;i<size;i++){

                  TreeNode tmpt = queue.poll();

                  l.add(tmpt.val);

                  System.out.println("val=="+tmpt.val);

                  if(tmpt.left != null){

                      queue.add(tmpt.left);

                  }

                  if(tmpt.right != null){

                      queue.add(tmpt.right);

                  }

              }

              map.put(h,l);

          }

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

          for(Integer k:map.keySet()){

              System.out.println("k=="+k);

              List<Integer> l = map.get(k);

              for(Integer i:l){

                System.out.print(i);

              }

              System.out.println("");

               result.put(k,l);

          }

     return result; 

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。