剑指offer--二叉搜索树与双向链表
来源:互联网 发布:算命最准的软件 编辑:程序博客网 时间:2024/06/02 04:24
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/**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) return null; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode pre = null; TreeNode p = root; boolean first = true; while (p != null || !stack.isEmpty()) { while (p != null) { stack.push(p); p = p.left; } p = stack.pop(); if (first) { root = p; pre = p; first = false; } else { pre.right = p; p.left = pre; pre = p; } p = p.right; } return root; } }
采用二叉树的中序遍历,第一个遍历的数,是这棵树中的最小值。所以作为双向链表的头结点,然后左子树的节点指向前一个节点。右子树节点指向后一个节点。
阅读全文
0 0
- 剑指Offer二叉搜索树与双向链表
- 【剑指offer:】Q27:二叉搜索树与双向链表
- 剑指offer--二叉搜索树与双向链表
- 剑指offer 27 - 二叉搜索树与双向链表
- 剑指offer-二叉搜索树与双向链表
- 《剑指offer》二叉搜索树与双向链表
- 【剑指Offer】二叉搜索树与双向链表
- 剑指offer—二叉搜索树与双向链表
- 剑指offer:二叉搜索树与双向链表
- 剑指offer-二叉搜索树与双向链表
- 剑指Offer--027-二叉搜索树与双向链表
- 剑指offer:二叉搜索树与双向链表
- [剑指offer]二叉搜索树与双向链表
- 《剑指offer》-二叉搜索树与双向链表
- 剑指offer-27二叉搜索树与双向链表
- 剑指offer题解 二叉搜索树与双向链表
- 剑指offer|二叉搜索树与双向链表
- 【剑指offer】二叉搜索树与双向链表
- python面向对象的简单应用
- python学习笔记
- LaTex 符号大全
- JZOJ 5441. 【NOIP2017提高A组冲刺11.1】序列
- ViewDragHelper (三)- 打造仿陌陌视频播放页(深入篇)
- 剑指offer--二叉搜索树与双向链表
- 数据结构-各类树
- 计算机视觉·常用数据集·3D
- 解决:redis添加hash数据失败问题
- 构建基于Node.js的web应用
- Java的内存机制
- HDU 5500 Reorder the Books
- maven生命周期(lifecycle)—— maven权威指南学习笔记(四)
- TCP/IP协议族【第五章IPV4地址】