144. 二叉树的前序遍历 - 力扣(LeetCode)

本章我们来探讨运用二叉树中所学的知识解决本题。对二叉树仍有疑问的小伙伴可以点击下方链接哦。
参考文献:(1条消息) 二叉树(三)_染柒_GRQ的博客-CSDN博客
首先我们来回顾一下解题原理:遍历顺序为 根,左子树和右右子树。
由于力扣是接口型O(J)题,所以我们先来看一下接口的含义。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/显然从这行代码可以看出,这是一个如图所示的链式结构。
链式结构
根据经验我们应该先写扩容,原因很简单,由于这是链式结构,所以一定要开辟空间。
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{int* a = (int*)malloc(sz * sizeof(int));return a;
}我们根据二叉树的实现可以再写一个计数函数。
int TreeSize(struct TreeNode* root)
{return root == NULL ? 0: TreeSize(root->left) + TreeSize(root->right) + 1;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{int sz = TreeSize(root);//开辟空间int* a = (int*)malloc(sz * sizeof(int));return a;
}最后一步就是开始遍历。
原理:遍历顺序为 根,左子树和右右子树。
int TreeSize(struct TreeNode* root)
{return root == NULL ? 0: TreeSize(root->left) + TreeSize(root->right) + 1;
}void _preOrder(struct TreeNode* root, int* a, int* pi)
{if(root == NULL){return;}a[*pi] = root->val;++(*pi);_preOrder(root->left, a, pi);_preOrder(root->right, a, pi);
}int* preorderTraversal(struct TreeNode* root, int* returnSize){int sz = TreeSize(root);//开辟数组int* a = (int*)malloc(sz * sizeof(int));int* i = 0;_preOrder(root, a, &i);*returnSize = sz;return a;
}记住传值与传址的区别。
当然根据我们在二叉树中的套路,我们可以把 i 定义为全局变量,但是要注意细节,我在这里也绕了点弯。
int i =0;
int TreeSize(struct TreeNode* root)
{return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}void _preOrder(struct TreeNode* root, int* a)
{if(root == NULL){return;}a[i] = root->val;++(i);_preOrder(root->left, a);_preOrder(root->right, a);
}int* preorderTraversal(struct TreeNode* root, int* returnSize)
{i = 0;int size = 0;int sz = TreeSize(root);//开辟空间int* a = (int*)malloc(sz * sizeof(int));_preOrder(root, a);*returnSize = sz;return a;
}本题其实在我们对二叉树有了一定了解以后做出来其实并不难,写不出来无非就是对代码的不熟练导致的,望小伙伴们勤加练习,更进一步!
欢迎大家点赞和评论!