思路:从下往上,从左往右进行循环压栈。
从根节点开始,将左儿子全部一步步压入栈中,若无左儿子了,从栈总弹出一个节点存储list中,将根节点变为弹出节点的右节点,继续以此为根节点的所有做儿子压栈,循环操作。下面贴代码。
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Create by yangshunfan
* 2018/4/3 21:44
* 二叉树的中序遍历
*/
public class Test67 {
public List<Integer> inorderTraversal(TreeNode root) {
// write your code here
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
stack.push(root);
do {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.empty()){
root = stack.pop();
list.add(root.val);
root = root.right;
}
} while (!stack.empty() || root != null);
return list;
}
}