[算法]二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路
因为是二叉搜索树,所以中序遍历就是有序的,这里采用非递归中序遍历,并通过前驱指针pre,进行转换。
代码
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.Stack; public class Solution { public TreeNode Convert(TreeNode pRootOfTree) { if (pRootOfTree == null) { return null; } Stack<TreeNode> stack = new Stack<>(); TreeNode pre = null;//用来标记上一个节点 TreeNode root = null;//用来返回头结点 boolean isFirst = true; while (!stack.isEmpty() || pRootOfTree != null) { if (pRootOfTree != null) { stack.push(pRootOfTree); pRootOfTree = pRootOfTree.left; } else { pRootOfTree = stack.pop(); if(isFirst){ root = pRootOfTree; pre = pRootOfTree; isFirst = false; }else{ pre.right = pRootOfTree; pRootOfTree.left = pre; pre = pRootOfTree; } pRootOfTree = pRootOfTree.right; } } return root; } }