Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12.  
  13. public class Solution {
  14. /**
  15. * @param root: a TreeNode
  16. * @return: a list of integer
  17. */
  18. public List<Integer> boundaryOfBinaryTree(TreeNode root) {
  19. List<Integer> result = new ArrayList<>();
  20.  
  21. if (root.left == null) {
  22. result.add(root.val);
  23. } else {
  24. getLeftSide(root, result);
  25. result.remove(result.size() - 1);
  26. }
  27. int leftSize = result.size();
  28. getBottomSide(root, result);
  29. if (root.right != null) {
  30. result.remove(result.size() - 1);
  31. getRightSide(root, result);
  32. result.remove(result.size() - 1);
  33. }
  34. return result;
  35. }
  36. private void getLeftSide(TreeNode root, List<Integer> result) {
  37. if (root != null) {
  38. result.add(root.val);
  39. if (root.left != null) {
  40. getLeftSide(root.left, result);
  41. } else {
  42. getLeftSide(root.right, result);
  43. }
  44. }
  45. }
  46.  
  47. private void getBottomSide(TreeNode root, List<Integer> result) {
  48. if (root != null) {
  49. if (root.left == null && root.right == null) {
  50. result.add(root.val);
  51. } else {
  52. getBottomSide(root.left, result);
  53. getBottomSide(root.right, result);
  54. }
  55. }
  56. }
  57.  
  58. private void getRightSide(TreeNode root, List<Integer> result) {
  59. if (root != null) {
  60. if (root.right != null) {
  61. getRightSide(root.right, result);
  62. } else {
  63. getRightSide(root.left, result);
  64. }
  65. result.add(root.val);
  66. }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement