Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. List<Integer> answer = new ArrayList<Integer>();
  12. Stack<TreeNode> stack = new Stack<TreeNode>();
  13. /*
  14. public List<Integer> inorderTraversal(TreeNode root) {
  15. if(root != null){
  16. inorderTraversal(root.left);
  17. answer.add(root.val);
  18. inorderTraversal(root.right);
  19. }
  20. return answer;
  21. */
  22. public List<Integer> inorderTraversal(TreeNode root) {
  23. if(root == null){
  24. return answer;
  25. }
  26. if(root.left == null && root.right == null){
  27. answer.add(root.val);
  28. return answer;
  29. }
  30. stack.push(root);
  31. while(root.left != null || root.right != null){
  32. while(root.left != null){
  33. stack.push(root.left);
  34. root = root.left;
  35. }
  36. answer.add(stack.peek().val);
  37. if(root.right != null){
  38. root = root.right;
  39. stack.pop();
  40. stack.push(root);
  41. } else {
  42. stack.pop();
  43. stack.peek().left = null;
  44. }
  45. }
  46. while(!stack.isEmpty()){
  47. answer.add(stack.pop().val);
  48. }
  49. return answer;
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement