Friday, October 30, 2015

[leetcode] Binary Tree Inorder Traversal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        if (root == null){
         return result;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);
        root = root.left;
        while(!stack.isEmpty()){
     if (root == null){
         TreeNode temp = stack.pop();
  result.add(temp.val);
  root = temp.right;
      }
      if (root != null){
          stack.push(root);
   root = root.left;
      }
 }

        return result;
    }
}

No comments:

Post a Comment