Recursively traverse Binary Trees and recursively calendar Binary Trees

Source: Internet
Author: User

Recursively traverse Binary Trees and recursively calendar Binary Trees
Problem
Recursively traverse Binary Trees

Ideas
The methods used to traverse Binary Trees are breadth-first and depth-first. The following describes depth-first.

Take the binary tree as an example:



Define three symbol tags first:

  • Access Node itself (N)
  • Traverse the left subtree of the node (L)
  • Traverse the right subtree of the node (R)
There are four methods:

The above number is traversed according to the above four methods, and the result is:

1. preorder: 1 2 4 7 5 3 6 8 9
2. inorder: 7 4 2 5 1 8 6 9 3
3. postorder: 7 4 5 2 8 9 6 3 1
4. level-order: 1 2 3 4 5 6 7 8 9

The following uses recursion to solve this problem.

Solution (Python)
#! /Usr/bin/env python # coding: utf-8from collections import namedtuplefrom sys import stdoutNode = namedtuple ('node', 'Data, left, right') tree = Node (1, node (2, Node (4, Node (7, None, None), None), Node (5, None, None), Node (3, Node (6, node (8, None, None), Node (9, None, None), None) # preorder (NLR) def preorder (node): if node is not None: print node. data, preorder (node. left) preorder (node. right) # LNR def inorder (node): if node is not None: inorder (node. left) print node. data, inorder (node. right) # LRN def postorder (node): if node is not None: postorder (node. left) postorder (node. right) print node. data, # sequence (levelorder) def levelorder (node, more = None): if node is not None: if more is None: more = [] more + = [node. left, node. right] print node. data, if more: levelorder (more [0], more [1:]) if _ name __= = "_ main _" print 'preorder :', preorder (tree) print '\ t \ n inorder:', inorder (tree) print '\ t \ n postorder:', postorder (tree) print '\ t \ nlevelorder: ', levelorder (tree) print' \ N'

Statement

For the source code, please go to algorithm in my github and find it. The file name is binary_tree_traversal.py.



Establish a binary tree first-order traversal (using recursive methods) C language source code

# Include <iostream. h>
# Include <stdio. h>
Struct tree
{
Char d;
Struct tree * lc, * rc;
};
Struct tree * create ()
{
Struct tree * p;
Char c;
Cout <"Enter the node :";
Fflush (stdin );
Cin> c;
If (c = '#') return 0;
P = new struct tree;
P-> d = c;
P-> lc = create ();
P-> rc = create ();
Return p;
}
Void first (struct tree * q)
{
If (! Q) return;
Cout <q-> d <",";
First (q-> lc );
First (q-> rc );
}
Void last (struct tree * q)
{
If (! Q) return;
Last (q-> lc );
Last (q-> rc );
Cout <q-> d <",";
}
Void mid (struct tree * q)
{
If (! Q) return;
Mid (q-> lc );
Cout <q-> d <",";
Mid (q-> rc );
}
Int heigh (struct tree * q)
{
Int lh, rh;
If (q = 0) return 0;
Lh = heigh (q-> lc );
Rh = heigh (q-> rc );
Return (lh> rh? Lh: rh) + 1;
}
Void main ()
{
Struct tree * head;
Head = create ();
Cout <"the height of the tree is:" Cout <"sorted in the forward order :";
First (head );
Cout <endl;
Cout <"in ascending order :";
Mid (head );
Cout <endl;
Cout <"is sorted in the following order :";
Last (head );
Cout <endl;
}

If the input '#' is null
Haha

Build a binary tree and traverse the sequence and sequence (either recursive or non-recursive)

// Declare the class BiTree and the definition structure BiNode. The file name is bitree. h.
# Ifndef BITREE_H
# Define BITREE_H

Template <class T>
Struct BiNode // The node Structure of the Binary Tree
{
T data;
BiNode <T> * lchild, * rchild;
};

Template <class T>
Class BiTree
{
Public:
BiTree (); // constructor, initializes a binary tree, and its forward sequence is input by the keyboard
~ BiTree (void); // destructor to release the storage space of each node in the binary linked list
BiNode <T> * Getroot (); // get the pointer to the root node
Void PreOrder (BiNode <T> * root); // PreOrder traversal of Binary Trees
Void InOrder (BiNode <T> * root); // traverses Binary Trees in ascending order.
Void PostOrder (BiNode <T> * root); // traverses Binary Trees in descending order.
Void LeverOrder (BiNode <T> * root); // sequence traversal Binary Tree
Private:
BiNode <T> * root; // header pointer to the root node
BiNode <T> * Creat (); // calls a constructor with Parameters
Void Release (BiNode <T> * root); // destructor call
};
# Endif

// Define the member function in the class. The file name is bitree. cpp.
# Include <iostream>
# Include <string>
# Include "bitree. h"
Using namespace std;

/*
* Precondition: the binary tree does not exist.
* Input: None
* Function: Construct a binary tree
* Output: None
* Post condition: generate a binary tree
*/
Template <class T>
BiTree <T>: BiTree ()
{
This-> root = Creat ();
}
/*
* Preconditions: a binary tree already exists.
* Input: None
* Function: Release the storage space of each node in the binary linked list.
* Output: None
* Post condition: the binary tree does not exist.
*/
Template <class T>
BiTree <T> ::~ BiTree (void)
{
Release (root );
}
/*
* Preconditions: a binary tree already exists.
* Input: None
* Function: Obtain the pointer to the root node of a binary tree.
* Output: pointer to the root node of a binary tree
* Post condition: the binary tree remains unchanged.
*/
Template <class T>
BiNode <T> * BiTree <T>: Getroot ()
{
R... the remaining full text>

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.