Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- public List<Integer> boundaryOfBinaryTree(TreeNode root) {
- List<Integer> ret = new ArrayList<Integer>();
- if(root == null) {
- return ret;
- }
- ret.add(root.val);
- collectLeftBoundaryAndLeaves(root.left, ret, true);
- collectRightLeavesAndBoundary(root.right, ret, true);
- return ret;
- }
- private void collectLeftBoundaryAndLeaves(TreeNode root, List<Integer> ret, boolean boundary) {
- if(root == null) {
- return;
- }
- if(root.left == null && root.right == null) {
- ret.add(root.val);
- return;
- }
- if(boundary) {
- ret.add(root.val);
- }
- if(root.left != null) {
- collectLeftBoundaryAndLeaves(root.left, ret, boundary);
- collectLeftBoundaryAndLeaves(root.right, ret, false);
- } else {
- collectLeftBoundaryAndLeaves(root.right, ret, boundary);
- }
- }
- private void collectRightLeavesAndBoundary(TreeNode root, List<Integer> ret, boolean boundary) {
- if(root == null) {
- return;
- }
- if(root.left == null && root.right == null) {
- ret.add(root.val);
- return;
- }
- if(root.right != null) {
- collectRightLeavesAndBoundary(root.left, ret, false);
- collectRightLeavesAndBoundary(root.right, ret, boundary);
- } else {
- collectRightLeavesAndBoundary(root.left, ret, boundary);
- }
- if(boundary) {
- ret.add(root.val);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement