1. Description
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?
2. Ideas
A. Go through the left subtree until the left child is empty
B. Then see if the right subtree of the current node is empty, is empty, then accesses the current node, pops up the current node, re-judges it, does not empty, accesses the current node, pops the current node, and returns the right child of the current node into the stack, returning a
C. It is important to note that after the current node is ejected, it is determined whether the stack is empty before the current node at the top of the stack is obtained
3. Code
Public list<integer> inordertraversal (TreeNode root) { list<integer>list=new Arraylist<integer > (); if (root==null) return list; Stack<treenode>st=new stack<treenode> (); St.push (root); TreeNode Top=null; while (!st.empty ()) { top=st.peek (); while (Top.left!=null) { st.push (top.left); Top=top.left; } while (Top.right==null) { list.add (top.val); St.pop (); if (!st.empty ()) Top=st.peek (); else break ; } if (!st.empty ()) { list.add (top.val); St.pop (); St.push (top.right); } } return list; }
4. Results
Leetcode_94_binary Tree inorder Traversal