|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 慵懒的勤快孩儿 于 2020-7-5 21:56 编辑
若二叉树为空,则空操作返回,否则先访问根结点,然后前序遍历左子树,再前序遍历右子树。(为了方便理解,大佬的图让我搬过来了,嘿嘿嘿)
C语言实现:
- /**
- * 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* preorderTraversal(struct TreeNode* root, int* returnSize){
- struct TreeNode *stack[1000];//数组代替栈
- int top = -1;//栈空
- int *result = (int*)malloc(sizeof(int) * 100);
- int i = 0;
- stack[++top] = root;
- while(top != -1){
- root = stack[top--];
- while(root){
- result[i++] = root->val;
- stack[++top] = root->right;
- root = root->left;
- }
- }
- *returnSize = i;
- //printf("%d",*returnSize);
- return result;
- }
复制代码 |
|