树的中序遍历(非递归)
左中右, 先入栈再输出
1.从根开始将结点入栈,并依次将左孩子入栈
2.直到左孩子为空,弹出栈中节点,输出该节点,并将右孩子入栈,重复1
3.若右孩子为空,弹出栈中节点,输出该节点,并将右孩子入栈,重复1
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
双向链表:左孩子指向上一节点,右孩子指向下一节点
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
List<TreeNode> tmpList = new ArrayList<>();
dfs(pRootOfTree, tmpList);
TreeNode head = tmpList.get(0);
TreeNode tmp = head;
tmp.left = null;
for(int i = 1; i < tmpList.size(); i++){
tmp.right = tmpList.get(i);
tmpList.get(i).left = tmp;
tmp = tmp.right;
}
return head;
}
private void dfs(TreeNode pRootOfTree,List<TreeNode> tmpList){
if(pRootOfTree == null){
return;
}
dfs(pRootOfTree.left,tmpList);
tmpList.add(pRootOfTree);
dfs(pRootOfTree.right,tmpList);
}
}