/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int countNodes(struct TreeNode* root){ if(root == NULL) return 0; return 1+countNodes(root->left)+countNodes(root->right); } void inorder(struct TreeNode* root,int *ret,int* returnSize) { if (!root) { return NULL; } inorder(root->left,ret, returnSize); ret[*returnSize] = root->val; (*returnSize)++; inorder(root->right,ret,returnSize); } bool arrayIsSort(int *ret,int num) { for(int i=0;i < num-1;i++) { if (ret[i] >= ret[i+1]) { return false; } } return true; } /* 中序遍历是有序的 将中序遍历的结果放入到一个数组中,然后判断该数组是否为有序的 */ bool isValidBST(struct TreeNode* root){ // 1. 计算树的长度 int len; len = countNodes(root); // 2. 开辟存储树节点的值的存储空间 int *ret; ret = malloc(sizeof(int) * len); int n = 0; // 3. 中序遍历,将树的节点放入到数组中,有一个变量标记 inorder(root,ret,&n); bool res; // 4. 判断数组的节点是否是有序的 i,j res = arrayIsSort(ret,n); return res; }
递归:找重复性,抵制人肉递归的诱惑
自定向下的编程思想,将所需函数定义以及参数写出来,然后将所有变量定义好,然后填充定义好的函数
一开始的时候计算二叉树节点个数的时候写成了计算层数,然后计算节点个数使用约算,使用 2^n,一直觉得^这个符号是用来算次方的,后来调试的时候发现错了,应该使用pow(2,n)
int treeLength(struct TreeNode *root) { if (!root) { return 0; } return treeLength(root->left) > treeLength(root->right) ? treeLength(root->left)+1 : treeLength(root->right) + 1; }
后来参考 https://leetcode.com/problems/validate-binary-search-tree/discuss/182864/C-Solution-4ms 中的求节点个数
来源:https://www.cnblogs.com/zhangpengfei5945/p/12163688.html