Given a binary tree, return the_inorder_traversal of its nodes' values.
Copy Input:
[1,null,2,3]
1
\
2
/
3
Output:
[1,3,2]
Copy /**
* 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) {
List < Integer > result = new ArrayList < Integer >();
recursiveInorderTravesal(root , result) ;
return result;
}
void recursiveInorderTravesal ( TreeNode root , List < Integer > result) {
if (root != null ) {
if ( root . left != null ) {
recursiveInorderTravesal( root . left , result) ;
}
result . add ( root . val );
if ( root . right != null ) {
recursiveInorderTravesal( root . right , result) ;
}
}
}
}
Copy public class Solution {
public List < Integer > inorderTraversal ( TreeNode root) {
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || ! stack . isEmpty ()) {
while (curr != null ) {
stack . push (curr);
curr = curr . left ;
}
curr = stack . pop ();
res . add ( curr . val );
curr = curr . right ;
}
return res;
}
}
Copy public List< Integer > inorderTraversal( TreeNode root) {
List < Integer > result = new ArrayList <>();
Deque < TreeNode > stack = new ArrayDeque <>();
TreeNode p = root;
while ( ! stack . isEmpty () || p != null ) {
if (p != null ) {
stack . push (p);
p = p . left ;
} else {
TreeNode node = stack . pop ();
result . add ( node . val ); // Add after all left children
p = node . right ;
}
}
return result;
}