在二叉树的模块中,最常用的遍历方法就是前序、中序、后序遍历,且经常结合递归的方法对树进行操作
前序遍历:按照访问根节点——左子树——右子树的方式遍历这棵树,而在访问左子树或者右子树的时候,我们按照同样的方式遍历,直到遍历完整棵树。
中序遍历:按照访问左子树——根节点——右子树的方式遍历这棵树,而在访问左子树或者右子树的时候我们按照同样的方式遍历,直到遍历完整棵树。
后序遍历:按照访问左子树——右子树——根节点的方式遍历这棵树,而在访问左子树或者右子树的时候,我们按照同样的方式遍历,直到遍历完整棵树。
给你二叉树的根节点 root
,返回它节点值的 前序 ,中序,后序遍历
前序遍历:递归
/**
* 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().
*/
void preorder(struct TreeNode*root,int *res,int *resSize)
{
if(root==NULL)
return;
res[(*resSize)++]=root->val;
preorder(root->left,res,resSize);
preorder(root->right,res,resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* res=malloc(sizeof(int)*2000);
*returnSize=0;
preorder(root,res,returnSize);
return res;
}
中序遍历:递归
/**
* 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().
*/
void inorder(struct TreeNode* root, int* res, int* resSize) {
if (!root) {
return;
}
inorder(root->left, res, resSize);
res[(*resSize)++] = root->val;
inorder(root->right, res, resSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = malloc(sizeof(int) * 501);
*returnSize = 0;
inorder(root, res, returnSize);
return res;
}
除了递归还可以用一个栈去维护
/**
* 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* inorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize = 0;
int* res = malloc(sizeof(int) * 501);
struct TreeNode** stk = malloc(sizeof(struct TreeNode*) * 501);
int top = 0;
while (root != NULL || top > 0) {
while (root != NULL) {
stk[top++] = root;
root = root->left;
}
root = stk[--top];
res[(*returnSize)++] = root->val;
root = root->right;
}
return res;
}
后序遍历:递归
/**
* 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().
*/
void postorder(struct TreeNode* root, int* res, int* resSize)
{
if (root == NULL)
return;
postorder(root->left, res, resSize);
postorder(root->right, res, resSize);
res[(*resSize)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = malloc(sizeof(int) * 2000);
*returnSize = 0;
postorder(root, res, returnSize);
return res;
}
树的遍历除了使用递归的方法,通常的还有迭代和Morris遍历,详细的请看另一篇文章。