二叉搜索树与双向链表
来源:互联网 发布:搜狗拼音输入法mac版 编辑:程序博客网 时间:2024/06/15 08:19
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
递归
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { TreeNode head = null; TreeNode realHead = null; public TreeNode Convert(TreeNode pRootOfTree) { ConvertSub(pRootOfTree); return realHead; } public void ConvertSub(TreeNode pRootOfTree) { if(pRootOfTree==null) return; ConvertSub(pRootOfTree.left); if(head == null) { head = pRootOfTree; realHead = pRootOfTree; } else {//把根节点插入到双向链表右边,head向后移动 head.right = pRootOfTree; pRootOfTree.left = head; head = pRootOfTree; } ConvertSub(pRootOfTree.right); }}非递归
/**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 pRootOfTree; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = pRootOfTree; TreeNode pre = null;// 用于保存中序遍历序列的上一节点 Boolean c = true; while(p!=null || !stack.empty()) { while(p!=null) { stack.push(p); p = p.left; } p = stack.pop(); if(c) { pRootOfTree = p; pre = pRootOfTree; c = false; } else { pre.right = p; p.left = pre; pre = p; } p = p.right; } return pRootOfTree; }}
阅读全文
0 0
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 二叉搜索树与双向链表
- 想说爱你不容易
- LeetCode--Two Pointers
- 1032. 挖掘机技术哪家强(20)
- tomcat8.5 配置
- 深度学习在推荐领域的应用
- 二叉搜索树与双向链表
- 时间戳服务与存在证明
- ACL简介
- extern "C"
- Linux中Locale及shell编码问题
- [MFC] Visual Studio工程文件清理工具V1.0
- 纳税服务系统【登陆、权限拦截、页面嵌套】
- TCP/IP 理解 3
- Vertx搭建Web服务器