145. Binary Tree Postorder Traversal(C语言)
后序遍历二叉树
题目
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
解答
递归遍历
/**
* 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().
*/
#define MAX_NUM 101
int i;
void Tra(struct TreeNode* root, int *ret)
{
if(root == NULL)
return ;
Tra(root->left, ret);
Tra(root->right, ret);
ret[i] = root->val;
i++;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
i = 0;
int *ret = (int *)malloc(sizeof(int)*MAX_NUM);
Tra(root, ret);
*returnSize = i;
return ret;
}
总结
后序遍历二叉树的递归函数结构:
void Tra(root, ...)
{
if(root == NULL)
...
Tra(root->left, ...);
Tra(root->right, ...);
...(其他在一个节点的操作)
}