题目
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

代码一

非递归方法
思想:将中序遍历(左根右)的数据压缩到栈中,然后每次取出栈顶元素作为当前节点关联到上一个节点

  1. public class Solution {
  2. public TreeNode Convert(TreeNode pRootOfTree) {
  3. if(pRootOfTree==null)return null;
  4. //用栈去保存要遍历的路径
  5. Stack<TreeNode> stack = new Stack<TreeNode>();
  6. TreeNode p = pRootOfTree;
  7. TreeNode pre = null;//用来存放中序遍历 的上一节点
  8. Boolean isFirst = true;
  9. while(p!=null||!stack.isEmpty())
  10. {
  11. //遍历左子树
  12. while(p!=null)
  13. {
  14. stack.push(p);
  15. p=p.left;
  16. }
  17. p=stack.pop();
  18. if(isFirst) {//将中序遍历的第一个节点标记为pRootOfTree;
  19. pRootOfTree = p;
  20. pre = pRootOfTree;
  21. isFirst = false;
  22. }else
  23. {
  24. pre.right = p;
  25. p.left = pre;
  26. pre = p;
  27. }
  28. p=p.right;
  29. }
  30. return pRootOfTree;
  31. }
  32. }

代码二

递归方法
思想:中序遍历的递归

  1. public class Solution {
  2. TreeNode pre = null;
  3. TreeNode root = null;
  4. public TreeNode Convert(TreeNode pRootOfTree) {
  5. if (pRootOfTree==null)return null;
  6. Convert(pRootOfTree.left);
  7. if(root==null)
  8. {
  9. root = pRootOfTree;
  10. }
  11. if(pre!=null)
  12. {
  13. pre.right = pRootOfTree;
  14. pRootOfTree.left = pre;
  15. }
  16. pre = pRootOfTree;
  17. Convert(pRootOfTree.right);
  18. return root;
  19. }
  20. }

代码三

思想:
中序遍历二叉树,然后用一个ArrayList类保存遍历的结果,这样在ArratList中节点就按顺序保存了,然后再来修改指针

  1. import java.util.ArrayList;
  2. public class Solution {
  3. public TreeNode Convert(TreeNode pRootOfTree) {
  4. if (pRootOfTree==null)
  5. return null;
  6. ArrayList<TreeNode> list=new ArrayList<>();
  7. Convert(list,pRootOfTree);
  8. return Convert(list);
  9. }
  10. public void Convert(ArrayList<TreeNode>list,TreeNode root){
  11. if (root!=null){
  12. Convert(list,root.left);
  13. list.add(root);
  14. Convert(list,root.right);
  15. }
  16. }
  17. public TreeNode Convert(ArrayList<TreeNode> list){
  18. TreeNode head=list.get(0);
  19. TreeNode cur=head;
  20. for (int i=1;i<list.size();++i){
  21. TreeNode node=list.get(i);
  22. node.left=cur;
  23. cur.right=node;
  24. cur=node;
  25. }
  26. return head;
  27. }
  28. }