递归遍历
/**
* 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 pre(struct TreeNode* root,int* re,int* returnSize)
{
if(root == NULL)
return;
re[(*returnSize)++] = root->val;
pre(root->left,re,returnSize);
pre(root->right,re,returnSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = 0;
int *re = malloc(sizeof(int)*101);
pre(root,re,returnSize);
return re;
}
递归写法总结:
1.确定递归函数要哪些参数
2.确定单层递归逻辑:如上所示前序遍历先根节点,再左最后右。
3.确定终止条件:指向NULL时开始返回。
二叉树的迭代遍历(用栈模拟递归)
栈中要存放的是节点二分节点中的变量保证能够更新节点
栈是后进先出所以先将右节点压进去才能保证弹出来的是先左后右
自己画一画
/**
* 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_SIZE 100
// Defining the stack structure
typedef struct {
struct TreeNode* items[MAX_SIZE];
int top;
} Stack;
// Initializing the stack
void initialize(Stack *s) {
s->top = -1;
}
// Check if the stack is full
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// Check if the stack is empty
int isEmpty(Stack *s) {
return s->top == -1;
}
// Add elements into stack
void push(Stack *s, struct TreeNode* value) {
// Check if the stack is full
if (isFull(s)) {
printf("Stack is full\n");
} else {
s->top++;
s->items[s->top] = value;
}
}
// Remove element from stack
struct TreeNode* pop(Stack *s) {
// Check if the stack is empty
if (isEmpty(s)) {
printf("Stack is empty\n");
return NULL;
} else {
struct TreeNode* temp = s->items[s->top];
s->top--;
return temp;
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
Stack* s = (Stack*)malloc(sizeof(Stack));
*returnSize = 0;
int* ret = malloc(sizeof(int)*100);
if(root == NULL) return ret;
initialize(s);
push(s,root);
while(!isEmpty(s))
{
struct TreeNode* node = pop(s);
ret[(*returnSize)++] = node->val;
if(node->right) push(s,node->right);
if(node->left) push(s,node->left);
//root = node;没必要啊
}
return ret;
}