二叉搜索树与双向链表
题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
实现语言:Java
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public TreeNode Convert(TreeNode root) { if(root==null||root.left==null&&root.right==null){ return root; } TreeNode left=Convert(root.left); TreeNode node=left; while(node!=null&&node.right!=null){ node=node.right; } if(node!=null){ node.right=root; root.left=node; } TreeNode right=Convert(root.right); if(right!=null){ root.right=right; right.left=root; } return left!=null?left:root; } }
实现语言:Java
/** 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 root) { if(root==null||root.left==null&&root.right==null){ return root; } Stack<TreeNode> stk=new Stack<TreeNode>(); TreeNode node=null; while(root!=null||!stk.isEmpty()){ if(root!=null){ stk.push(root); root=root.right; }else{ root=stk.pop(); if(node==null){ node=root; }else{ node.left=root; root.right=node; node=root; } root=root.left; } } return node; } }