原题链接在这里:https://leetcode.com/problems/find-leaves-of-binary-tree/#/description
题目:
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]
.
题解:
计算当前node到leaf的距离为当前node的高度,相同高度的点放在同一个list里.
Time Complexity: O(n). leaf层用时n/2, leaf上一层用时n/4*2, 再上一层用时n/8*3. 是n(i/2^i)的和. i = 1,2,3....
Space: O(logn), stack space. Regardless res.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> findLeaves(TreeNode root) { 12 List<List<Integer>> res = new ArrayList<List<Integer>>(); 13 height(root, res); 14 return res; 15 } 16 17 private int height(TreeNode root, List<List<Integer>> res){ 18 if(root == null){ 19 return -1; 20 } 21 int h = 1+Math.max(height(root.left, res), height(root.right, res)); 22 if(res.size() < h+1){ 23 res.add(new ArrayList<Integer>()); 24 } 25 res.get(h).add(root.val); 26 return h; 27 } 28 }
类似Maximum Depth of Binary Tree.
时间: 2024-11-05 11:32:25