Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.
Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn’t have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.
The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.
The right-most node is also defined by the same way with left and right exchanged.
Example 1
Example 2
解法1:
参考了这篇的解法。
对于leaf我们可以用dfs来解决。似乎还需要两个function分别来存储left path和right path。那么在找寻left path的过程中,我们一直向左,如果碰到左面的节点就属于left path,如果还有右节点那么就用dfs搜索leaf。
对于right path也是一个原理。
对于rightPath函数的写法,要注意对于每一个节点,要先得出leaf node,再得出right node。因为题目要求是逆时针
Java