从stack中取出一个元素 重复上述行为(这里需要加入set集合记录访问过得left的节点 否则会出现重复访问的问题)
代码:
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> rs = new LinkedList<Integer>(); inorderTraversal(rs, root); return rs; } /** * recursive solution * @param result * @param root */ public void inorderTraversal(List<Integer> result,TreeNode root) { if(root == null)return; if(root.left != null) inorderTraversal(result, root.left); result.add(root.val); if(root.right != null) inorderTraversal(result, root.right); } /** * 中序遍历的非递归版本,记录访问标识set * @param root * @return */ public List<Integer> inorderTraversal2(TreeNode root) { List<Integer> rs = new LinkedList<Integer>(); Stack stack = new Stack(); if(root == null) return rs; stack.push(root); Set<TreeNode> set = new HashSet<TreeNode>(); while (! stack.isEmpty()){ TreeNode node = (TreeNode) stack.peek(); while (node.left != null){ if(!set.contains(node.left)) { stack.push(node.left); set.add(node.left); } else break; node = node.left; } node = (TreeNode) stack.pop(); rs.add(node.val); if(node.right !=null ) stack.push(node.right); } return rs; }
[LeetCode]Binary Tree Inorder Traversal
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45768753