用遞迴方式遍曆二叉樹,遞迴曆二叉樹

來源:互聯網
上載者:User

用遞迴方式遍曆二叉樹,遞迴曆二叉樹
問題
用遞迴方式遍曆二叉樹

思路說明
遍曆二叉樹的方法有廣度優先和深度優先兩類,下面闡述的是深度優先。

以的二叉樹為例:



先定義三個符號標記:

  • 訪問結點本身(N)
  • 遍曆該結點的左子樹(L)
  • 遍曆該結點的右子樹(R)
有四種方式:

上面的數,按照以上四種方式遍曆,得到的結果依次是:

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

下面用遞迴的方式,解決此題。

解決(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))#前序(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,#層序(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'

聲明

  源碼請到我的github中的algorithm尋找,檔案名稱為:binary_tree_traversal.py。



建立二叉樹的先序遍曆(用遞迴的方法)c語言原始碼

#include<iostream.h>
#include<stdio.h>
struct tree
{
char d;
struct tree *lc,*rc;
};
struct tree* create()
{
struct tree*p;
char c;
cout<<"請輸入結點:";
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<<"樹的高為:"<<heigh(head)<<endl;
cout<<"前序排列為:";
first(head);
cout<<endl;
cout<<"中序排列為:";
mid(head);
cout<<endl;
cout<<"後序排列為:";
last(head);
cout<<endl;
}

如果子為空白記的輸入‘#’代表空呀
哈哈
 
建立二叉樹,層序、先序遍曆( 用遞迴或非遞迴的方法都可以)

//聲明類BiTree及定義結構BiNode,檔案名稱為bitree.h
#ifndef BITREE_H
#define BITREE_H

template <class T>
struct BiNode //二叉樹的結點結構
{
T data;
BiNode<T> *lchild, *rchild;
};

template <class T>
class BiTree
{
public:
BiTree( ); //建構函式,初始化一棵二叉樹,其前序序列由鍵盤輸入
~BiTree(void); //解構函式,釋放二叉鏈表中各結點的儲存空間
BiNode<T>* Getroot(); //獲得指向根結點的指標
void PreOrder(BiNode<T> *root); //前序走訪二叉樹
void InOrder(BiNode<T> *root); //中序遍曆二叉樹
void PostOrder(BiNode<T> *root); //後序遍曆二叉樹
void LeverOrder(BiNode<T> *root); //層序遍曆二叉樹
private:
BiNode<T> *root; //指向根結點的頭指標
BiNode<T> *Creat( ); //有參建構函式調用
void Release(BiNode<T> *root); //解構函式調用
};
#endif

//定義類中的成員函數,檔案名稱為bitree.cpp
#include<iostream>
#include<string>
#include"bitree.h"
using namespace std;

/*
*前置條件:二叉樹不存在
*輸 入:無
*功 能:構造一棵二叉樹
*輸 出:無
*後置條件:產生一棵二叉樹
*/
template<class T>
BiTree<T>::BiTree( )
{
this->root = Creat( );
}
/*
*前置條件:二叉樹已存在
*輸 入:無
*功 能:釋放二叉鏈表中各結點的儲存空間
*輸 出:無
*後置條件:二叉樹不存在
*/
template<class T>
BiTree<T>::~BiTree(void)
{
Release(root);
}
/*
*前置條件:二叉樹已存在
*輸 入:無
*功 能:擷取指向二叉樹根結點的指標
*輸 出:指向二叉樹根結點的指標
*後置條件:二叉樹不變
*/
template<class T>
BiNode<T>* BiTree<T>::Getroot( )
{
r......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.