Given a binary tree, return the inorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3} ,
1 2 / 3
Return [1,3,2] .
Note:recursive solution is trivial, could do it iteratively?
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {//The first is a non-recursive solution://with the help of the stack data structure, the leftmost node is put into the stack, when the leftmost node is reached, the top of the stack pops up, fills in the result, then traverses the right node of the top of the stack .//The second is recursion, it's relatively simple. /*Public list<integer> inordertraversal (TreeNode root) {list<integer> res=new arraylist<integer& gt; (); Stack<treenode> stack=new stack<treenode> (); TreeNode Node=root; while (!stack.empty () | | Node!=null) {while (node!=null) {Stack.push (node); Node=node.left; } node=stack.pop (); Res.add (Node.val); Node=node.right; } return res; }*/List<Integer> res=NewArraylist<integer>(); PublicList<integer>inordertraversal (TreeNode root) {Getinorder (root); returnRes; } Public voidGetinorder (TreeNode root) {if(root==NULL)return; Inordertraversal (Root.left); Res.add (Root.val); Inordertraversal (Root.right); }}
[Leedcode 94] Binary Tree inorder Traversal