本题的思想,非递归中序遍历
使用map存每个节点的父节点
一个节点的下一个节点:
1)如果当前节点有右子树,则下一节点为右子树的最左节点
2)如果当前节点没有右子树,则下一个节点为当前节点的最小长辈(父、爷、祖父、曾祖父—)节点.left == 当前节点
如果当前节点的长辈节点们,都遍历到root的长辈null了,都没有.left == 当前节点的。则说明下一个节点为null
public class MidTree2 {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode n1 = new TreeNode(2);
TreeNode n2 = new TreeNode(3);
root.right = n1;
n1.left = n2;
List<Integer> midRes = midTreeNotRecursion(root);
System.out.println(midRes);
}
public static List<Integer> midTreeNotRecursion(TreeNode root) {
List<Integer> list = Lists.newArrayList();
if (root == null) {
return list;
}
if (root.left == null && root.right == null) {
list.add(root.val);
return list;
}
TreeNode temp = root;
Map<TreeNode, TreeNode> curAndParentMap = new HashMap<>();
curAndParentMap.put(root, null);
while (temp.left != null) {
curAndParentMap.put(temp.left, temp);
temp = temp.left;
}
// 1.初始节点
list.add(temp.val);
TreeNode curTreeNode = temp;
// 2.添加节点
while (true) {
TreeNode nextTreeNode = next(curAndParentMap, curTreeNode);
if (nextTreeNode == null) {
break;
}
list.add(nextTreeNode.val);
curTreeNode = nextTreeNode;
}
return list;
}
private static TreeNode next(Map<TreeNode, TreeNode> curAndParentMap, TreeNode curTreeNode) {
TreeNode next;
if (curTreeNode.right == null) {
TreeNode parent = curAndParentMap.get(curTreeNode);
while (true) {
if (parent == null) {
return null;
} else if (parent.left != null && Objects.equals(parent.left.val, curTreeNode.val)) {
return parent;
} else {
curTreeNode = parent;
parent = curAndParentMap.get(curTreeNode);
}
}
} else {
next = curTreeNode.right;
curAndParentMap.put(next, curTreeNode);
while (next.left != null) {
curAndParentMap.put(next.left, next);
next = next.left;
}
}
return next;
}
}