二叉树递归模板总结
101. 对称二叉树
bool isQ(TreeNode* root1,TreeNode* root2){ if(root1==nullptr&&root2==nullptr){ return true; } else if(root1==nullptr||root2==nullptr){ return false; } else if(root1->val!=root2->val){ return false; } return isQ(root1->left,root2->right)&&isQ(root1->right,root2->left); }
108. 将有序数组转换为二叉搜索树
TreeNode* h(vector<int>& nums,int left,int right){ if(left>right){ return nullptr; } int mid=(left+right)/2; TreeNode* root=new TreeNode(nums[mid]); root->left=h(nums,left,mid-1); root->right=h(nums,mid+1,right); return root; }
求树高
int forhigh(TreeNode* root){ if(root==nullptr){ return 0; } int l=forhigh(root->left); int r=forhigh(root->right); return max(l,r)+1; }