Topic:
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]
.
Train of thought: In the topic, the rule uses the loop instead of the recursive solution, uses the auxiliary stack to store the traversed node, if not empty then the stack, otherwise the stack assigns the value, and points to its right node.
Code:
Public classSolution { PublicList<integer>inordertraversal (TreeNode root) {List<Integer> req =NewArraylist<integer>(); if(Root = =NULL) returnreq; Stack<TreeNode> stack =NewStack<treenode>(); while(!stack.isempty () | | \ root! =NULL){ if(Root! =NULL) {Stack.push (root); Root=Root.left; }Else{TreeNode temp=Stack.pop (); Req.add (Temp.val); Root= Temp.right;//one of the most important steps } } returnreq; }}
Reference Link: http://www.programcreek.com/2012/12/leetcode-solution-of-binary-tree-inorder-traversal-in-java/
[Leetcode-java] Binary Tree inorder traversal