Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
Act I: recursive
/** * 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) { if(root == null) return result; inorder(root); return result; } public void inorder(TreeNode root) { if(root.left!=null) inorder(root.left); result.add(root.val); if(root.right!=null) inorder(root.right); } private List<Integer> result = new ArrayList<Integer>(); }
Method II: cycle. Use stack and a set mark whether the current node visited
/** * 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>(); Set<TreeNode> visitedSet = new HashSet<TreeNode>();//Set有HashSet和TreeSet两种实现 if(root == null) return result; Stack<The TreeNode> = S new new Stack <the TreeNode> (); the TreeNode curNode = the root; the while ( to true ) { IF (visitedSet.contains (curNode)) { // if accessed, access to the right son result.add (curNode.val) ; curNode = curNode.right; } the while (curNode =! null ) { // If you have not visited, advanced stack own, then left his son s.push (curNode); visitedSet.add (curNode); curNode = curNode.left ; } IF(s.empty ()) BREAK ; // pop a node curNode = s.peek (); s.pop (); } return Result; } }