题目来源:
力扣https://leetcode.cn/problems/binary-tree-inorder-traversal/题目简介:
给定一个二叉树的根节点root,返回他的中序遍历
思路(递归:
中序遍历就是先访问左子树,再访问根节点,再访问右子树,左子树的子树遍历也是如此,所以这样的遍历就具有天然的递归性质。
代码实现:
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)* 101);
//申请一个二级指针来存放指针的指针
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;
}