Binary Search Tree changes to sorted two-way linked list

Source: Internet
Author: User

Public class test {public node root; Public void insert (INT value) {root = insert (root, value);} public node insert (node, int value) {If (node = NULL) {node = new node (value);} else if (node. value> value) {node. left = insert (node. left, value);} else {node. right = insert (node. right, value);} return node;} public void print (node) {If (node! = NULL) {print (node. left); system. out. println (node. value); print (node. right) ;}} public void turn (node) {If (node! = NULL) {turn (node. left); turn (node. right); // connect the two sorted linked lists. // note the node temp = node in the leaf node status. left; while (temp! = NULL) {If (temp. Right = NULL) {break;} else {temp = temp. Right;} If (temp! = NULL) {node. Left = temp; temp. Right = node;} temp = node. Right; while (temp! = NULL) {If (temp. Left = NULL) {break;} else {temp = temp. Left;} If (temp! = NULL) {node. right = temp; temp. left = node ;}} public static void main (string [] ARGs) {test T = new test (); int [] A =, 16}; For (INT I = 0; I <. length; I ++) {T. insert (a [I]);} node = T. root; T. turn (node); system. out. println (T. root. value); system. out. println (T. root. left. value); system. out. println (T. root. left. left. value); system. out. println (T. root. left. left. left. value );}}

Tree: 10

6 14

4 8 12 16

Program output: 10 8 6 4

Is there a path for sum?

public boolean hasPath(Node node,int sum){if(node == null){return false;}if(node.value == sum){return true;}return hasPath(node.left,sum - node.value) ||   hasPath(node.right,sum - node.value);}

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.