94. Binary Tree Inorder Traversal java solutions
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
Subscribe to see which companies asked this question
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 public List<Integer> inorderTraversal(TreeNode root) { 12 ArrayList<Integer> ans = new ArrayList<Integer>(); 13 Stack<TreeNode> s = new Stack<TreeNode>(); 14 15 if(root == null) return ans; 16 s.push(root); 17 while(!s.isEmpty()){ 18 TreeNode node = s.peek(); 19 if(node.left != null){ 20 s.push(node.left); 21 node.left = null;//原先这里没有设置为null一直内存超出限制,过不去。不知道为什么, 22 }else{ 23 ans.add(node.val); 24 s.pop(); 25 if(node.right != null){ 26 s.push(node.right); 27 } 28 } 29 } 30 31 return ans; 32 } 33 }