26二叉搜索树与双向链表

题目描述

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

思路:

由于要求转换之后的链表是排好序的,我们可以中序遍历树的蒙一个节点。因为中序遍历是按照从小到大的顺序遍历二叉树的每一个结点。
把左右子树都转换成排序的双向链表之后再和根节点链接起来,整棵二叉树就转换成了排序的双向链表。

链接:https://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5
来源:牛客网

解题思路:
1.将左子树构造成双链表,并返回链表头节点。
2.定位至左子树双链表最后一个节点。
3.如果左子树链表不为空的话,将当前root追加到左子树链表。
4.将右子树构造成双链表,并返回链表头节点。
5.如果右子树链表不为空的话,将该链表追加到root节点之后。
6.根据左子树链表是否为空确定返回的节点。
 
 
 1 链接:https://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5
 2 来源:牛客网
 3 
 4     public TreeNode Convert(TreeNode root) {
 5         if(root==null)
 6             return null;
 7         if(root.left==null&&root.right==null)
 8             return root;
 9         // 1.将左子树构造成双链表,并返回链表头节点
10         TreeNode left = Convert(root.left);
11         TreeNode p = left;
12         // 2.定位至左子树双链表最后一个节点
13         while(p!=null&&p.right!=null){
14             p = p.right;
15         }
16         // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
17         if(left!=null){
18             p.right = root;
19             root.left = p;
20         }
21         // 4.将右子树构造成双链表,并返回链表头节点
22         TreeNode right = Convert(root.right);
23         // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
24         if(right!=null){
25             right.left = root;
26             root.right = right;
27         }
28         return left!=null?left:root;       
29     }
 
 
 
 1 public class Solution {
 2     TreeNode head = null;
 3     public TreeNode Convert(TreeNode root) {
 4         if(root==null) return null;
 5         
 6         Convert(root.right);
 7         if(head==null){//递归到最右边了的初始情况
 8             head=root;
 9         }
10         else{
11             head.left = root;
12             root.right=head;
13             head = root;
14         }
15         Convert(root.left);
16         return head;
17     }
18 }
原文地址:https://www.cnblogs.com/zle1992/p/8035140.html