输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
方法一:非递归版
解题思路:
核心是中序遍历的非递归算法
修改当前遍历的节点与前一遍历节点的指针指向。
1 /** 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 import java.util.Stack; 15 public class Solution { 16 public TreeNode Convert(TreeNode pRootOfTree) { 17 18 19 if(pRootOfTree==null) 20 return null; 21 Stack<TreeNode> stack = new Stack<TreeNode>(); 22 TreeNode p = pRootOfTree; 23 TreeNode pre = null;// 用于保存中序遍历序列的上一节点 24 boolean isFirst = true; 25 while(p!=null||!stack.isEmpty()){ 26 while(p!=null){ 27 stack.push(p); 28 p = p.left; 29 } 30 p = stack.pop(); 31 if(isFirst){ 32 pRootOfTree = p;// 将中序遍历序列中的第一个节点记为root 33 pre = pRootOfTree; 34 isFirst = false; 35 }else{ 36 pre.right = p; 37 p.left = pre; 38 pre = p; 39 } 40 p = p.right; 41 } 42 return pRootOfTree; 43 } 44 }
方法二:递归版
解题思路:
1
.将左子树构造成双链表,并返回链表头节点。
2
.定位至左子树双链表最后一个节点。
3
.如果左子树链表不为空的话,将当前root追加到左子树链表。
4
.将右子树构造成双链表,并返回链表头节点。
5
.如果右子树链表不为空的话,将该链表追加到root节点之后。
6
.根据左子树链表是否为空确定返回的节点。
1 /** 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 import java.util.Stack; 15 public class Solution { 16 public TreeNode Convert(TreeNode pRootOfTree) { 17 if(pRootOfTree==null) 18 return null; 19 if(pRootOfTree.left==null&&pRootOfTree.right==null) 20 return pRootOfTree; 21 // 1.将左子树构造成双链表,并返回链表头节点 22 TreeNode left = Convert(pRootOfTree.left); 23 TreeNode p = left; 24 // 2.定位至左子树双链表最后一个节点 25 while(p!=null&&p.right!=null){ 26 p = p.right; 27 } 28 // 3.如果左子树链表不为空的话,将当前root追加到左子树链表 29 if(left!=null){ 30 p.right = pRootOfTree; 31 pRootOfTree.left = p; 32 } 33 // 4.将右子树构造成双链表,并返回链表头节点 34 TreeNode right = Convert(pRootOfTree.right); 35 // 5.如果右子树链表不为空的话,将该链表追加到root节点之后 36 if(right!=null){ 37 right.left = pRootOfTree; 38 pRootOfTree.right = right; 39 } 40 return left!=null?left:pRootOfTree; 41 } 42 }