中序遍历:左子树,根节点,右子树。
一、递归中序遍历
public static void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.getLeft());
System.out.println(root.getValue());
inOrder(root.getRight());
}
二、非递归中序遍历
public static void inOrderIterative(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> treeNodeStack = new Stack<>();
TreeNode currentNode = root;
while (currentNode != null || !treeNodeStack.isEmpty()) {
while (currentNode != null) {
treeNodeStack.push(currentNode);
currentNode = currentNode.getLeft();
}
currentNode = treeNodeStack.pop();
System.out.println(currentNode.getValue());
currentNode = currentNode.getRight();
}
}
一次性找到最左边的节点。这个节点就可以马上出栈了。出栈后需要再遍历其右子树。。