Convert a Binary Tree to Doubly Linked List
来源:互联网 发布:r9网络不稳定怎么回事 编辑:程序博客网 时间:2024/06/06 23:19
/*Convert a binary search tree to doubly linked list with in-order traversal.ExampleGiven a binary search tree: 4 / \ 2 5 / \1 3return 1<->2<->3<->4<->5Tags Expand Linked List*/
/* Thoughts: Inorder with 1 stack: peek add left till end, pop and add, then push right node. Everytime when pop out a node and add, make it a new boubllistnode dNode.next = curr curr.pre = dNode.next dNode = dNode.next boarder case: if null, return a null.*/public class Solution { public DoublyListNode bstToDoublyList(TreeNode root) { if (root == null) { return null; } //Init stack Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root; stack.push(node); //Create DoublyListNode header DoublyListNode dummy = new DoublyListNode(0); DoublyListNode dNode = dummy; while(!stack.isEmpty()) { while (node != null && node.left != null) { stack.push(node.left); node = node.left; } //add node node = stack.pop(); DoublyListNode curr = new DoublyListNode(node.val); dNode.next = curr; curr.prev = dNode; dNode = dNode.next; //check right node and add to stack node = node.right; if (node != null) { stack.push(node); } } return dummy.next; }}
阅读全文
0 0
- Convert a Binary Tree to Doubly Linked List
- Convert Binary Search Tree (BST) to Sorted Doubly-Linked List
- Convert Binary Search Tree (BST) to Sorted Doubly-Linked List
- Leetcode优化:Convert a binary tree to linked list
- [LintCode] 将二叉查找树转换成双链表 Convert Binary Search Tree to Doubly Linked List
- Convert BST to Sorted Doubly-Linked List
- Convert a BST to a sorted doubly-linked list in-place
- Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s
- Convert Binary Search Tree to an Ordered Double Linked List
- Convert Binary Tree to Linked List By Depth
- 114. Flatten Binary Tree to Linked List\538. Convert BST to Greater Tree
- HWK:A doubly linked list using class
- (转)A Memory-Efficient Doubly Linked List
- 【Hackerrank】Reverse a doubly linked list
- A Memory-Efficient Doubly Linked List
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- 用原生js写滚动条
- MATLAB颜色的使用
- SQL数据库基本操作
- TapTap遭App Store下架 苹果热更新海啸来袭
- 在Intellij Idea创建部署第一个web项目(入门)
- Convert a Binary Tree to Doubly Linked List
- HDU-1166 线段树模板
- NAT技术
- mybatis学习之传统JDBC编程中的问题总结
- java 排序算法总结
- ZOJ 2734(Exchange Cards)
- maven的配置以及功能
- MAC下MySQL初始密码忘记怎么办
- Executor, ExecutorService 和 Executors 间的不同