offer-Two forks search tree and doubly linked list

Source: Internet
Author: User

Title: Enter a binary search tree to convert the two-fork search tree into a sorted doubly linked list. The space complexity is O (1).


The stupidest way to do this is to put the middle sequence traversal in an array or list and iterate through the concatenation again. But requires space complexity of O (1), there is no way to do so, this time can refer to this solution: http://blog.csdn.net/my_jobs/article/details/47666909 judge a tree is not a binary search tree, Can imitate the last method.

The subject is not the same as the solution of the book, feeling this slightly concise and good understanding, but are the model of the middle sequence traversal.

Private TreeNode pre = Null;private static TreeNode head = Null;public void convert (TreeNode root) {if (root = null) Retu Rn;convert (Root.left), if (pre! = null) {pre.right = Root;root.left = pre;} else {head = root;} Pre = Root;convert (root.right);}

The final head is the table header of the transformed list. Or that kind of summary, in the tree this data structure, many templates are can be applied, for example, did the above problem, the following one is easy to transform out. A comparison reveals that the code is really similar. Many of the tree's tool-like methods, such as the tree's hierarchical traversal, the height of the tree and so on, can be memorized, and then transformed.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

offer-Two forks search tree and doubly linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.