Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. public class Solution {
  2. public List<Integer> boundaryOfBinaryTree(TreeNode root) {
  3. List<Integer> ret = new ArrayList<Integer>();
  4. if(root == null) {
  5. return ret;
  6. }
  7.  
  8. ret.add(root.val);
  9. collectLeftBoundaryAndLeaves(root.left, ret, true);
  10. collectRightLeavesAndBoundary(root.right, ret, true);
  11. return ret;
  12. }
  13.  
  14. private void collectLeftBoundaryAndLeaves(TreeNode root, List<Integer> ret, boolean boundary) {
  15. if(root == null) {
  16. return;
  17. }
  18.  
  19. if(root.left == null && root.right == null) {
  20. ret.add(root.val);
  21. return;
  22. }
  23.  
  24. if(boundary) {
  25. ret.add(root.val);
  26. }
  27.  
  28. if(root.left != null) {
  29. collectLeftBoundaryAndLeaves(root.left, ret, boundary);
  30. collectLeftBoundaryAndLeaves(root.right, ret, false);
  31. } else {
  32. collectLeftBoundaryAndLeaves(root.right, ret, boundary);
  33. }
  34. }
  35.  
  36. private void collectRightLeavesAndBoundary(TreeNode root, List<Integer> ret, boolean boundary) {
  37. if(root == null) {
  38. return;
  39. }
  40.  
  41. if(root.left == null && root.right == null) {
  42. ret.add(root.val);
  43. return;
  44. }
  45.  
  46. if(root.right != null) {
  47. collectRightLeavesAndBoundary(root.left, ret, false);
  48. collectRightLeavesAndBoundary(root.right, ret, boundary);
  49. } else {
  50. collectRightLeavesAndBoundary(root.left, ret, boundary);
  51. }
  52.  
  53. if(boundary) {
  54. ret.add(root.val);
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement