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.node
Example:
Given binary tree
1
/ 2 3
/ 4 5
Returns [4, 5, 3], [2], [1].算法
Explanation:優化
給一顆二叉樹,
返回這個二叉樹的葉子節點,每一次一組,依次放在List中this
個人思路:每一次深度遍歷收割一次葉子放在結果中(缺點:深度有多少,就要深度遍歷多少次)
優化算法:深度優選搜索,葉子節點深度標記爲0,其餘節點的深度標記爲左右葉子節點較大的深度+1;相同深度的放在一個結果節點中code
public List<List<Integer>> FindLeaves(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); while (root != null) { List<Integer> re = new ArrayList<>(); if (DFSTree(root, re)) { root = null; } result.add(re); } return result; } private boolean DFSTree(TreeNode root, List<Integer> re) { if (root.left == null && root.right == null) { re.add(root.val); return true; } if (root.left != null) { if (DFSTree(root.left, re)) { root.left = null; } } if (root.right != null) { if (DFSTree(root.right, re)) { root.right = null; } } return false; }
public List<List<Integer>> FindLeavesOptimize(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); DFSTreeOptimize(root, result); return result; } private int DFSTreeOptimize(TreeNode root, List<List<Integer>> result) { if (root.left == null && root.right == null) { if (result.size() <= 0) { result.add(0, new ArrayList<>()); } result.get(0).add(root.val); return 0; } int deep, leftDeep = 0, rightDeep = 0; if (root.left != null) { leftDeep = DFSTreeOptimize(root.left, result); } if (root.right != null) { rightDeep = DFSTreeOptimize(root.right, result); } deep = Math.max(leftDeep, rightDeep) + 1; if (result.size() <= deep) { result.add(deep, new ArrayList<>()); } result.get(deep).add(root.val); return deep; }