zoukankan      html  css  js  c++  java
  • 二叉树三种顺序遍历应用

    1.非递归,不允许用栈,求前序遍历最后一个结点

    思想:前序遍历最后一个结点:若有右子树,则为右子树最右下结点,若有左子树,则为左子树最右下结点,否则为根结点。

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    typedef struct BTreeNode
    {
    	int data;
    	struct BTreeNode *lchild,*rchild;
    }BTree;
    int _tmain(int argc, _TCHAR* argv[])
    {
    	return 0;
    }
    BTree *LastNode(BTree *b)
    {
    	BTree *p=b;
    	if(p==NULL)return NULL;
    	else while(p)
    	{
    		if(p->rchild)p=p->rchild;
    		else if(p->lchild)p=p->lchild;
    		else return p;
    	}
    }
    

    2.满二叉树后序转化为前序递归

    思想:对于满二叉树,根据任意一个遍历可将其转化为其他遍历

    BTree PostToPre(int post[],int pre[],int l1,int h1,int l2,int h2)//后转前,l1,h1,l2,h2分别为序列初始后结束结点下标
    {
    	if(h1>l1)
    	{
    		pre[h2]=post[h1];//根结点
    		int half=(h1-l1)/2;//左子树或右子树的结点数
    		PostToPre(post,pre,l1,l1+half-1,l2+1,l2+half);//左子树后序转前序
    		PostToPre(post,pre,l1+half,h1-1,l2+half+1,h2);//右子树后序转前序
    	}
    }
    
  • 相关阅读:
    单例模式
    关于static
    在O(1)时间复杂度删除链表节点
    奇偶分割数组
    用栈实现队列
    前序遍历和中序遍历树构造二叉树
    扇贝每日一句_1006
    寻找旋转排序数组中的最小值
    翻转链表
    扇贝每日一句_1002
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/2637034.html
Copyright © 2011-2022 走看看