中序遍歷:左子樹,根節點,右子樹。
一、遞歸中序遍歷
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();
}
}
一次性找到最左邊的節點。這個節點就可以馬上出棧了。出棧后需要再遍歷其右子樹。。