二叉搜索树与双向链表

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 
 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 public class Solution {
15     TreeNode lastNode;
16     public void dfs(TreeNode p) {
17         if (p == null) return;
18         TreeNode l = p.left;
19         TreeNode r = p.right;
20         p.left = p.right = null;
21         dfs(l);
22         p.left = lastNode;
23         lastNode.right = p;
24         lastNode = p;
25         dfs(r);
26     }
27     public TreeNode Convert(TreeNode pRootOfTree) {
28         if (pRootOfTree == null) return null;
29         TreeNode dummy = new TreeNode(0);
30         lastNode = dummy;
31         dfs(pRootOfTree);
32         dummy.right.left = null;
33         return dummy.right;
34     }
35 }

 

posted @ 2020-02-22 09:58  hyx1  阅读(109)  评论(0编辑  收藏  举报