常德市住房和城乡建设局网站,1688外贸网站,巢湖城市建设投资有限公司网站,wordpress破图Leetcode Leetcode -94.二叉树的中序遍历Leetcode -145.二叉树的后序遍历 Leetcode -94.二叉树的中序遍历
题目#xff1a;给定一个二叉树的根节点 root #xff0c;返回 它的 中序 遍历 。
示例 1#xff1a; 输入#xff1a;root [1, null, 2, 3] 输出#xff1a;[1,… Leetcode Leetcode -94.二叉树的中序遍历Leetcode -145.二叉树的后序遍历 Leetcode -94.二叉树的中序遍历
题目给定一个二叉树的根节点 root 返回 它的 中序 遍历 。
示例 1 输入root [1, null, 2, 3] 输出[1, 3, 2]
示例 2 输入root [] 输出[]
示例 3 输入root [1] 输出[1]
提示 树中节点数目在范围[0, 100] 内
100 Node.val 100
思路二叉树的中序遍历化为子问题先遍历当前根的左子树再打印当前根的值最后遍历当前根的右子树 void Inorder(struct TreeNode* root, int* a, int* pos){if (root NULL)return;//先递归当前根的左子树再将当前根的 val 存放到数组中最后递归当前根的右子树Inorder(root-left, a, pos);a[(*pos)] root-val;Inorder(root-right, a, pos);}int* inorderTraversal(struct TreeNode* root, int* returnSize){//开辟一个返回中序遍历的数组pos记录数组的长度int* ret (int*)malloc(sizeof(int) * 100);int pos 0;//进入中序遍历Inorder(root, ret, pos);*returnSize pos;return ret;}Leetcode -145.二叉树的后序遍历
题目给你一棵二叉树的根节点 root 返回其节点值的 后序遍历 。
示例 1 输入root [1, null, 2, 3] 输出[3, 2, 1]
示例 2 输入root [] 输出[]
示例 3 输入root [1] 输出[1]
提示 树中节点的数目在范围[0, 100] 内
100 Node.val 100
思路二叉树的后序遍历化为子问题先遍历当前根的左子树再遍历当前根的右子树最后打印当前根的值 void Postorder(struct TreeNode* root, int* a, int* pos){if (root NULL)return;//先递归当前根的左子树再递归当前根的右子树最后将当前根的 val 存放到数组中Postorder(root-left, a, pos);Postorder(root-right, a, pos);a[(*pos)] root-val;}int* postorderTraversal(struct TreeNode* root, int* returnSize){//开辟返回的数组int* ret (int*)malloc(sizeof(int) * 100);int pos 0;//进入后序遍历Postorder(root, ret, pos);*returnSize pos;return ret;}