• 366. Find Leaves of Binary Tree



    /* * 366. Find Leaves of Binary Tree * 2016-7-15 by Mingyang * 这道题目非常的有意思,一层一层的打印出叶子节点并且移除掉 * 我开始的想法就是dfs,自底向上的方法,我想每一层的增加,list的index也增加 * 到叶子节点时候,list的index就是在最后,所以打印出来的就是反的list,再reverse一下 * 但是出现了一个问题!就是左右子树的叶子节点的depth不同步,因为左子树depth为3,右为2 * 走到左边的leave就是3,右边就是2! * 所以问题在于: * 还是应该按照顺序打出,并且以height作为index!而不是从root一个一个传下来的index * 而是应该index一个一个传上去,这样就不会出现问题了,因为左右子树的叶子depth是一样的! */ private static List<List<Integer>> ress = new ArrayList<List<Integer>>(); public static List<List<Integer>> findLeaves1(TreeNode root) { helper(root); return ress; } private static int helper(TreeNode node) { if (null == node) return -1; int height = 1 + Math.max(helper(node.left), helper(node.right)); if (ress.size() < height + 1) ress.add(new ArrayList<Integer>()); ress.get(height).add(node.val); // if need to actually remove the leaves, uncomment next line node.left = node.right = null; return height; } //我的错误的代码,但是方法很接近了 public static List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> res=new ArrayList<List<Integer>>(); dfs(res,root,0); Collections.reverse(res); root=null; return res; } public static boolean dfs(List<List<Integer>> res,TreeNode root,int index){ if(root==null) return true; if(dfs(res,root.left,index+1)&&dfs(res,root.right,index+1)){ root.left=null; root.right=null; while(res.size()<=index) res.add(new ArrayList<Integer>()); res.get(index).add(root.val); return true; } return false; }
  • 相关阅读:
    快速排序
    冒泡排序
    mysql 拷贝表插入新的表
    http协议
    nginx错误日志error_log日志级别
    MySQL数据库远程访问的权限
    mysql create database 指定utf-8编码
    MYSQL日志
    linux常用命令
    java学习--基础知识进阶第六天--集合&迭代器、增强for & 泛型、常见数据结构、List子体系
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5676030.html
Copyright © 2020-2023  润新知