Find Leaves of Binary Tree
来源:互联网 发布:西昊 ergomax 知乎 编辑:程序博客网 时间:2024/05/01 23:46
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Given binary tree
1 / \ 2 3 / \ 4 5
Returns [4, 5, 3], [2], [1]
.
Explanation:
1. Removing the leaves [4, 5, 3]
would result in this tree:
1 / 2
2. Now removing the leaf [2]
would result in this tree:
1
3. Now removing the leaf [1]
would result in the empty tree:
[]
Returns [4, 5, 3], [2], [1]
.
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> lists = new ArrayList<List<Integer>>(); if(root == null) return lists; collect(root, lists); return lists; } public int collect(TreeNode root, List<List<Integer>> lists){ if(root == null) return 0; int leftdepth = collect(root.left, lists); int rightdepth = collect(root.right, lists); int curdepth = Math.max(leftdepth, rightdepth)+1; if(lists.size() < curdepth){ List<Integer> list = new ArrayList<Integer>(); list.add(root.val); lists.add(list); } else { lists.get(curdepth-1).add(root.val); } return curdepth; }}
0 0
- Find Leaves of Binary Tree
- Find Leaves of Binary Tree
- Find Leaves of Binary Tree
- LeetCode 366. Find Leaves of Binary Tree
- LeetCode 366. Find Leaves of Binary Tree
- LeetCode 366. Find Leaves of Binary Tree
- 366. Find Leaves of Binary Tree
- 366. Find Leaves of Binary Tree
- [leetcode] 366. Find Leaves of Binary Tree 解题报告
- Medium 366题 Find Leaves of Binary Tree
- Leetcode 366. Find Leaves of Binary Tree (Medium) (cpp)
- [Leetcode] 366. Find Leaves of Binary Tree 解题报告
- geeksforgeeks Find the maximum path sum between two leaves of a binary tree
- C++: Find height of a Binary Tree
- leetcode 530. Minimum Absolute Difference in BST/404. Sum of Left Leaves/563. Binary Tree Tilt
- Find distance between two given keys of a Binary Tree
- Find deepest node(s) of a binary tree
- LeetCode(二)563. Binary Tree Tilt&404.Sum of Left Leaves&108.Convert Sorted Array to BST
- MySQL 数据类型
- memset
- 关于“u盘打开为空,但是占用空间”的解决方法之一
- 视频处理vout_frame_buffer_ctrl模块的理解
- java爬虫
- Find Leaves of Binary Tree
- 视角的选择和坐标变换
- JAVA核心编成基础篇(1)
- POJ 2891 Strange Way to Express Integers(中国剩余定理)
- 《JavaScipt高级程序设计》总结五
- 一、C Call Lua
- 【NOI OJ】4977 怪盗基德的滑翔翼
- apatch POI excel---->pdf
- 一个苦逼程序员遇到的面试题目