输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
- 中序遍历
- 用before指针记录上一个被访问的节点
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
Stack<TreeNode> stack = new Stack<>();
TreeNode index = pRootOfTree;
TreeNode before = null;
TreeNode root = null;
while(!stack.isEmpty()||index!=null){
while(index != null){
stack.push(index);
index = index.left;
}
if(!stack.isEmpty()){
index = stack.pop();
before = modifyPointer(before,index);
if(root == null) root = before;
index = index.right;
}
}
return root;
}
public TreeNode modifyPointer(TreeNode before, TreeNode index){
if(before != null) {
before.right = index;
index.left = before;
}
return index;
}
}
网友评论