/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*//**
* Note: The returned array must be malloced, assume caller calls free().
*/structstack{int top;structTreeNode*stk[100];};int*preorderTraversal(structTreeNode* root,int* returnSize){int*array =(int*)malloc(sizeof(int)*100);structstack*st =(structstack*)malloc(sizeof(*st));structTreeNode*node = root;memset(st,0,sizeof(*st));
st->top =-1;*returnSize =0;if(root ==NULL){return array;}while(st->top >-1|| node !=NULL){while(node !=NULL){
array[(*returnSize)++]= node->val;
st->stk[++st->top]= node;
node = node->left;}
node = st->stk[st->top--];
node = node->right;}printf("%d\n",*returnSize);return array;}
解3:Morris 遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*//**
* Note: The returned array must be malloced, assume caller calls free().
*/int*preorderTraversal(structTreeNode* root,int* returnSize){int*array =(int*)malloc(sizeof(int)*100);structTreeNode*cur = root,*pre =NULL;*returnSize =0;if(root ==NULL){return array;}while(cur !=NULL){
pre = cur->left;if(pre !=NULL){while(pre->right !=NULL&& pre->right != cur){
pre = pre->right;}if(pre->right ==NULL){
array[(*returnSize)++]= cur->val;
pre->right = cur;
cur = cur->left;continue;}else{
pre->right =NULL;}}else{
array[(*returnSize)++]= cur->val;}
cur = cur->right;}return array;}
145. 二叉树的后序遍历
解1: 递归
voidpostorder(structTreeNode*root,int*ans,int*returnSize){if(root !=NULL){postorder(root->left, ans, returnSize);postorder(root->right, ans, returnSize);
ans[(*returnSize)++]= root->val;}}int*postorderTraversal(structTreeNode* root,int* returnSize){int*ans =(int*)malloc(sizeof(int)*100);*returnSize =0;postorder(root, ans, returnSize);return ans;}
解2: 迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*//**
* Note: The returned array must be malloced, assume caller calls free().
*/structstack{int top;structTreeNode*stk[100];};voidreverse(int*array,int n){int left =0, right = n-1;int tmp;while(left < right){
tmp = array[left];
array[left]= array[right];
array[right]= tmp;
left++, right--;}}int*postorderTraversal(structTreeNode* root,int* returnSize){int*array =(int*)malloc(sizeof(int)*100);structstack*st =(structstack*)malloc(sizeof(*st));structTreeNode*node =NULL;memset(st,0,sizeof(*st));
st->top =-1;*returnSize =0;if(root ==NULL){return array;}
st->stk[++st->top]= root;while(st->top >-1){
node = st->stk[st->top--];
array[(*returnSize)++]= node->val;if(node->left) st->stk[++st->top]= node->left;if(node->right) st->stk[++st->top]= node->right;}reverse(array,*returnSize);return array;}