题目:给定一颗二叉树,用非递归方法中序遍历这颗二叉树
算法:
从某个节点node出发
1. 向左遍历,边遍历边将节点压入栈
2. 到达左子树的尽头,从栈中取出节点node并访问值
3. 转向node节点的右子树
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * Algorithm: * * 从某个节点node出发 * 1. 向左遍历,边遍历边将节点压入栈 * 2. 到达左子树的尽头,从栈中取出节点node并访问值 * 3. 转向node节点的右子树 */ public List<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> inorderList = new ArrayList<Integer>(); TreeNode node = root; while (null!=node || !stack.empty()) { while (null != node) { stack.add(node); node = node.left; } if (!stack.empty()) { node = stack.pop(); inorderList.add(node.val); node = node.right; } } return inorderList; } }
[LeetCode]Binary Tree Inorder Traversal,布布扣,bubuko.com
[LeetCode]Binary Tree Inorder Traversal
原文:http://blog.csdn.net/yeweiouyang/article/details/37761747