Boundary of Binary Tree
程序员文章站
2022-04-02 18:17:26
...
Input:
1
\
2
/ \
3 4
Ouput:
[1, 3, 4, 2]
Explanation:
The root doesn't have left subtree, so the root itself is left boundary.
The leaves are node 3 and 4.
The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.
So order them in anti-clockwise without duplicates and we have [1,3,4,2].
Input:
____1_____
/ \
2 3
/ \ /
4 5 6
/ \ / \
7 8 9 10
Ouput:
[1,2,4,7,8,9,10,6,3]
Explanation:
The left boundary are node 1,2,4. (4 is the left-most node according to definition)
The leaves are node 4,7,8,9,10.
The right boundary are node 1,3,6,10. (10 is the right-most node).
So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].
思路:这题tricky的地方就是,如果从root开始收集好了,会有重复,而且left,leaves,right也会有重复。
怎么避免重复,就是分别收集root.left, root.right两个分支的left, leave, leave, right;
左右下角重复的点,全部由leave收集,左右两边边不收集root.left == null && root.right == null 的点;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) {
return list;
}
list.add(root.val);
collectLeft(root.left, list);
collectLeaves(root.left, list);
collectLeaves(root.right, list);
collectRight(root.right, list);
return list;
}
private void collectLeaves(TreeNode node, List<Integer> list) {
if(node == null) {
return;
}
if(node.left == null && node.right == null) {
list.add(node.val);
return;
}
collectLeaves(node.left, list);
collectLeaves(node.right, list);
}
private void collectLeft(TreeNode node, List<Integer> list) {
if(node == null || (node.left == null && node.right == null)) {
return;
}
if(node.left != null) {
list.add(node.val);
collectLeft(node.left, list);
} else {
list.add(node.val);
collectLeft(node.right, list);
}
}
private void collectRight(TreeNode node, List<Integer> list) {
if(node == null || (node.left == null && node.right == null)) {
return;
}
if(node.right != null) {
collectRight(node.right, list);
list.add(node.val);
} else {
collectRight(node.left, list);
list.add(node.val);
}
}
}
推荐阅读
-
EasyUI Tree树组件无限循环实例分析
-
完全掌握MySql之写入Binary Log的流程
-
二分查找(Binary Search)需要注意的问题,以及在数据库内核中的
-
Oracle B树索引简介(B-Tree Index)
-
关于mysql字符集设置了character_set_client=binary 在gbk情况下会出现表描述是乱码的情况
-
二分查找(Binary Search)需要注意的问题,以及在数据库内核中的
-
教你通过B+Tree平衡多叉树理解InnoDB引擎的聚集和非聚集索引
-
MySQL:Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEM
-
完全掌握MySql之写入Binary Log的流程
-
【POJ.3321】Apple Tree(树状数组)