二叉树知识回顾——【树】之二叉树(C语言)(含图解)_半生瓜のblog-CSDN博客
二叉树的前序遍历
144. 二叉树的前序遍历 - 力扣(LeetCode) (leetcode-cn.com)
本题中,对于C++或者Java等语言,返回的是它们的数据结构库里面的数据结构,而C语言没有,这也就是如果用C语言往后通吃数据结构会困难的原因。
注意本体的传参,操作的是不是一个数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
int TreeSize(struct TreeNode* root) { return root == NULL?0:TreeSize(root->left)+TreeSize(root->right)+1; } void _preorder(struct TreeNode* root,int* a,int *i) { if(root == NULL) { return ; } a[*i] = root->val; (*i)++; _preorder(root->left,a,i); _preorder(root->right,a,i); } int* preorderTraversal(struct TreeNode* root, int* returnSize){ int size = TreeSize(root); int* a = (int*)malloc(size*sizeof(int)); int i = 0; _preorder(root,a,&i); *returnSize = size; return a; }
|
二叉树的最大深度
经典的分治问题
104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)
一棵树的高度就是最长路径的结点个数。
本质上用的后序遍历,先求左,后求右边,再求自己。
图示
![image-20210618084730107](/images/LeetCode%E5%88%B7%E9%A2%98(9)%E3%80%90%E6%A0%91%E3%80%91%E5%89%8D%E5%BA%8F&%E5%B9%B3%E8%A1%A1&%E6%B7%B1%E5%BA%A6.assets/image-20210618084730107.png)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int maxDepth(struct TreeNode* root){ if(root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth?leftDepth+1:rightDepth+1; }
|
平衡二叉树
Loading Question… - 力扣(LeetCode) (leetcode-cn.com)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
int maxDepth(struct TreeNode* root){ if(root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth?leftDepth+1:rightDepth+1; }
bool isBalanced(struct TreeNode* root){ if(root == NULL) { return true; } int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return abs(leftDepth-rightDepth) < 2 && isBalanced(root->left) && isBalanced(root->right); }
|