原题题目
代码实现(首刷自解)
# define MAX 1001
void visit ( struct TreeNode * root, int * returnSize, int * arr)
{
if ( root)
{
visit ( root-> left, returnSize, arr) ;
visit ( root-> right, returnSize, arr) ;
arr[ ( * returnSize) ++ ] = root-> val;
}
}
int * postorderTraversal ( struct TreeNode * root, int * returnSize) {
int * arr = ( int * ) malloc ( sizeof ( struct TreeNode ) * MAX) ;
( * returnSize) = 0 ;
visit ( root, returnSize, arr) ;
return arr;
}
代码实现(二刷Morris)(抄的代码太难理解了)
void addPath ( int * vec, int * vecSize, struct TreeNode * node) {
int count = 0 ;
while ( node != NULL ) {
++ count;
vec[ ( * vecSize) ++ ] = node-> val;
node = node-> right;
}
for ( int i = ( * vecSize) - count, j = ( * vecSize) - 1 ; i < j; ++ i, -- j) {
int t = vec[ i] ;
vec[ i] = vec[ j] ;
vec[ j] = t;
}
}
int * postorderTraversal ( struct TreeNode * root, int * returnSize) {
int * res = malloc ( sizeof ( int ) * 2001 ) ;
* returnSize = 0 ;
if ( root == NULL ) {
return res;
}
struct TreeNode * p1 = root, * p2 = NULL ;
while ( p1 != NULL ) {
p2 = p1-> left;
if ( p2 != NULL ) {
while ( p2-> right != NULL && p2-> right != p1) {
p2 = p2-> right;
}
if ( p2-> right == NULL ) {
p2-> right = p1;
p1 = p1-> left;
continue ;
} else {
p2-> right = NULL ;
addPath ( res, returnSize, p1-> left) ;
}
}
p1 = p1-> right;
}
addPath ( res, returnSize, root) ;
return res;
}
代码实现(迭代 纯迭代也挺难理解的 就用了reverse 借助一个数组+一个栈)(前序遍历把先访问左子数边为右子树 然后翻转)
# define MAX 2001
int * postorderTraversal ( struct TreeNode * root, int * returnSize) {
int * res = malloc ( sizeof ( int ) * MAX) , size = 0 ;
* returnSize = 0 ;
int arr[ MAX] = { 0 } ;
struct TreeNode * stack[ MAX] , * position = root;
while ( position != NULL || size > 0 )
{
while ( position != NULL )
{
stack[ size++ ] = position;
arr[ ( * returnSize) ++ ] = position-> val;
position = position-> right;
}
position = stack[ -- size] ;
position = position-> left;
}
int i = * returnSize - 1 , j;
for ( j= 0 ; j < * returnSize ; )
res[ j++ ] = arr[ i-- ] ;
return res;
}
代码实现(三刷自解)
class Solution {
public :
vector< int > postorderTraversal ( TreeNode* root) {
stack< TreeNode* > stack;
vector< int > ans;
TreeNode* ptr = root, * pre = nullptr ;
while ( ! stack. empty ( ) || ptr) {
while ( ptr) {
stack. emplace ( ptr) ;
ptr = ptr-> left;
}
ptr = stack. top ( ) ;
if ( ! ptr-> right || ptr-> right == pre) {
ans. emplace_back ( ptr-> val) ;
pre = ptr;
stack. pop ( ) ;
ptr = nullptr ;
} else {
ptr = ptr-> right;
}
}
return ans;
}
} ;
代码实现(四刷自解 DAY 15 golang)
func postorderTraversal ( root * TreeNode) [ ] int {
stack, ptr := make ( [ ] * TreeNode, 0 ) , root
var pre * TreeNode
ret := make ( [ ] int , 0 )
for ptr != nil || len ( stack) != 0 {
for ptr != nil {
stack = append ( stack, ptr)
ptr = ptr. Left
}
tmpptr := stack[ len ( stack) - 1 ]
if tmpptr. Right == pre || tmpptr. Right == nil {
ret = append ( ret, tmpptr. Val)
stack = stack[ : len ( stack) - 1 ]
ptr = nil
pre = tmpptr
} else {
ptr = tmpptr. Right
}
}
return ret
}