Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public List<Integer> inorderTraversal(TreeNode root) {
- //stack to traverse the tree
- Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
- //list to hold the inorder traversal
- List<Integer> list = new LinkedList<Integer>();
- // if (root != null){
- // recInorder(list, root);
- // }
- //traversal temp var
- TreeNode curr = root;
- //while loop to fill out the list
- while (curr != null || !stack.isEmpty()){
- //first push to the stack all of the root's left nodes until theres a null
- while(curr != null){
- stack.push(curr);
- curr = curr.left;
- }
- //once you've hit the bottom of the left subtree, get the last
- //one that was put it
- if (!stack.isEmpty()){
- curr = stack.pop();
- }
- //and put it in the list
- list.add(curr.val);
- //then shift over to that node's right subtree and begin the process of going
- //down the left subtree again (if there are any right/left subtrees)
- //tho the if not nulls in the whiles deal with this
- curr = curr.right;
- }
- return list;
- }
- public void recInorder(List<Integer> list, TreeNode root){
- if (root.left != null){
- recInorder(list, root.left);
- }
- list.add(root.val);
- if (root.right != null){
- recInorder(list, root.right);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement