leetcode145 Binary Tree Postorder Traversal
一、问题描述
给定一个二叉树,返回它的节点值的后序遍历。---使用非递归实现
二、解题思路
非递归后序遍历 --- 左右根
对于一个节点而言,要实现访问顺序为左儿子-右儿子-根节点,可以利用后进先出的栈,在节点不为空的前提下,依次将根,右,左压栈。故需要按照根-右-左的顺序遍历树,而先序遍历的顺序是根-左-右,故只需将先序遍历的左右调换并把访问方式打印改为压入另一个栈即可。最后一起打印栈中的元素
step1:将当前结点同时入临时栈和结果栈【根】,并遍历右子树----【右】
step2:当右子树遍历结束后,弹出临时栈栈顶结点,并遍历其左子树----【左】,继续step1步骤
step3:当所有结点都访问完,即最后访问的树节点为空且临时栈也为空时,主算法结束,依次pop出结果栈结点
参考链接:https://www.cnblogs.com/llhthinker/p/4747962.html
三、算法实现
1、栈数据结构建立及二叉树数据结构定义
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/**二叉树数据结构定义**/
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
/**栈数据结构引入**/
#define MAXSIZE 10000
#define OVERFLOW 0
#define error -65530
/**栈的数据结构定义**/
typedef struct Sq_stack
{
struct TreeNode data[MAXSIZE];
int top;
}Sq_stack;
/**栈的创建--初始化**/
void initStack(Sq_stack *S)
{
S = (Sq_stack*)malloc(sizeof(Sq_stack));
if(!S)
exit(OVERFLOW);//栈空间分配失败
S->top = 0; //栈顶元素从0开始算起
}
/**插入栈顶元素e**/
bool Push(Sq_stack *S, struct TreeNode* e)
{
/**插入栈顶元素:判断栈是否已满**/
if( S->top == MAXSIZE-1 )
return false;
S->top++;
S->data[S->top] = *e;
return true;
}
/**删除栈顶元素,并用节点承接**/
struct TreeNode* Pop(Sq_stack *S)
{
/**删除栈顶元素:判断栈是否为空**/
if(S->top == 0)
return NULL;
struct TreeNode* e = (struct TreeNode*)malloc(sizeof(struct TreeNode));
*e = S->data[S->top];
S->top--;
return e;
}
bool isEmptyStack( Sq_stack *S )
{
return S->top == 0?true:false;
}
2、后序遍历非递归实现算法
/****************************************
Author:tmw
date:2018-5-7
****************************************/
/**
*returnSize:用于返回结果数组的大小
---结果用自定义的*result数组存储,它的长度传给*returnSize
**/
int* postorderTraversal(struct TreeNode* root, int* returnSize)
{
if( root == NULL ) return NULL;
/**自定义结果数组并初始化**/
int* result = (int*)malloc(1000*sizeof(int));
int len = 0;
/**定义栈并初始化**/
Sq_stack* stk_result = (Sq_stack*)malloc(sizeof(Sq_stack));
initStack(stk_result);
Sq_stack* temp_stk = (Sq_stack*)malloc(sizeof(Sq_stack));
initStack(temp_stk);
while( root || !isEmptyStack(temp_stk) )
{
/**将当前结点同时入临时栈和结果栈【根】,并遍历右子树----【右】**/
while( root )
{
Push(temp_stk,root);
Push(stk_result,root);
root = root->right;
}
/**当右子树遍历结束后,弹出临时栈栈顶结点,并遍历其左子树----【左】,继续while**/
if( !isEmptyStack(temp_stk) )
{
root = Pop(temp_stk);
root = root->left;
}
}
/**
当所有结点都访问完,即最后访问的树节点为空且临时栈也为空时,
主算法结束,依次pop出结果栈结点
**/
struct TreeNode* e = (struct TreeNode*)malloc(sizeof(struct TreeNode));
while( !isEmptyStack(stk_result) )
{
e = Pop(stk_result);
result[len++] = e->val;
}
free(e);
*returnSize = len;
return result;
}
四、执行结果
leetcode accept
python版
def travel(root):
stack = []
stack_tmp = []
result = []
while root or stack_tmp:
while root:
stack.append(root) # 根
stack_tmp.append(root)
root = root.right # 右
if stack_tmp:
root = stack_tmp.pop()
root = root.left # 左
while stack:
node = stack.pop()
result.append(node)
return result
梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙~~~