Implementation of binary tree and four kinds of common traversal (python) __python

Source: Internet
Author: User

Constructing a Node class


Constructs the tree class and increases the method of adding nodes


Pre-sequence traversal (root, left, right), sequence traversal (left, Root, right), sequential traversal (left, right, root)


Using queues to achieve breadth-first traversal, that is, hierarchical traversal


There are two main types of traversal of the reference tree, one is the depth-first traversal, the first order, the sequence, the second, and the other is the breadth-first traversal, like the hierarchical traversal. The difference between the two is not very obvious in the tree structure, but the efficiency and function of depth-first search and breadth-first search are very different when we extend from the tree to the direction graph and to the direction-free graph.
The depth first generally uses the recursion, the breadth first generally uses the queue. Most of the algorithms that can be implemented by recursion can also be implemented using stacks.

My impression is that there is a recursive structure of the tree method, but I have not been thinking how to construct. After a careful thought, recursive thinking is somewhat similar to depth-first algorithm, and tree construction should be breadth first. If you use recursion, you must have a termination condition, such as a rule tree depth. Otherwise, the tree will be constructed in favor of the left tree or the right list tree. Therefore, the construction of the general tree or should be used in the queue better.



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.