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 的点;
注意点:整个是个逆时针收集的过程,collectLeft跟collectRight是不一样的,left是先收集node,然后再收集左边,左边,左边,如果没有左边,收集右边。Right是下面的right收集好了,如果没有right,收集左边,再collect当前node。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> list = new ArrayList<>();
list.add(root.val);
collectleft(root.left, list);
collectleave(root.left, list);
collectleave(root.right, list);
collectright(root.right,list);
return list;
}
public void collectleft(TreeNode root, List<Integer> list) {
if(root == null || (root.left == null && root.right == null)) {
return;
}
list.add(root.val);
if(root.left != null) {
collectleft(root.left, list);
} else {
collectleft(root.right, list);
}
}
public void collectleave(TreeNode root, List<Integer> list) {
if(root == null) {
return;
}
if(root.left == null && root.right == null) {
list.add(root.val);
}
collectleave(root.left, list);
collectleave(root.right, list);
}
public void collectright(TreeNode root, List<Integer> list) {
if(root == null || (root.left == null && root.right == null)) {
return;
}
if(root.right != null) {
collectright(root.right, list);
} else {
collectright(root.left, list);
}
list.add(root.val);
}
}