Leetcode
Leetcode -94. In-order traversal of binary tree
Question : Given the root node root of a binary tree, return its in-order traversal.
Example 1:
Input: root = [1, null, 2, 3]
Output: [1, 3, 2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Tip:
The number of nodes in the tree is in the range [0, 100]
- 100 <= Node.val <= 100
Idea : In-order traversal of a binary tree is turned into a sub-problem: first traverse the left subtree of the current root, then print the value of the current root, and finally traverse the right subtree of the current root;
void Inorder(struct TreeNode* root, int* a, int* pos)
{
if (root == NULL)
return;
//先递归当前根的左子树;再将当前根的 val 存放到数组中;最后递归当前根的右子树
Inorder(root->left, a, pos);
a[(*pos)++] = root->val;
Inorder(root->right, a, pos);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
//开辟一个返回中序遍历的数组,pos记录数组的长度
int* ret = (int*)malloc(sizeof(int) * 100);
int pos = 0;
//进入中序遍历
Inorder(root, ret, &pos);
*returnSize = pos;
return ret;
}
Leetcode -145. Post-order traversal of binary tree
Question : Given the root node root of a binary tree, return the post-order traversal of its node value.
Example 1:
Input: root = [1, null, 2, 3]
Output: [3, 2, 1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Tip:
The number of nodes in the tree is in the range [0, 100]
- 100 <= Node.val <= 100
Idea : Post-order traversal of a binary tree is turned into a sub-problem: first traverse the left subtree of the current root, then traverse the right subtree of the current root, and finally print the value of the current root;
void Postorder(struct TreeNode* root, int* a, int* pos)
{
if (root == NULL)
return;
//先递归当前根的左子树;再递归当前根的右子树;最后将当前根的 val 存放到数组中
Postorder(root->left, a, pos);
Postorder(root->right, a, pos);
a[(*pos)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize)
{
//开辟返回的数组
int* ret = (int*)malloc(sizeof(int) * 100);
int pos = 0;
//进入后序遍历
Postorder(root, ret, &pos);
*returnSize = pos;
return ret;
}