Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to convert python binary tree linked lists to each other

Shulou Source: shulou.com Published: 2022-06-01 14:11:56 09月10日 Update

Today, I will talk to you about how to convert python binary tree linked lists to each other. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

A, ordered linked list conversion binary search tree

Given a single linked list, the elements are sorted in ascending order and converted to a highly balanced binary search tree.

In this problem, a highly balanced binary tree means that the absolute value of the height difference between the left and right subtrees of each node of a binary tree is not more than 1.

Example:

Given ordered linked list: [- 10,-3, 0, 5, 9]

One possible answer is: [0,-3, 9,-10, null, 5], which can represent the following highly balanced binary search tree:

0

/\

-3 9

/ /

-10 5

Ideas for solving the problem:

1. The absolute value of the left and right height of the balanced binary tree does not exceed 1, so the middle element of the linked list is the root element.

2, balance binary tree left child right child tree head-> right child tree tail

4, pay attention to the boundary situation

/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode *} * / func flatten (root * TreeNode) {flatten1 (root)

}

Func flatten1 (root * TreeNode) (head,tail * TreeNode) {if root==nil {return nil,nil} l:=root.Left r:=root.Right if lumped telephone & r==nil {return root,root} if l==nil {hr,tr:=flatten1 (r) root.Left=nil root.Right=hr return root,tr} if r==nil {h T:=flatten1 (l) root.Right=h root.Left=nil return root,t} h Performing flatten1 (l) root.Right=h root.Left=nil hr,tr:=flatten1 (r) t.Right=hr return root,tr} read the above content Do you have any further understanding of how to convert python binary tree linked lists to each other? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Children subtrees elements height content search order ideas situations absolute values nodes boundaries two ascending order half in place arrays time and space more this topic Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Apple Shulou Technology Shulou Tech Info Linux