int HeightOfBinaryTree(BinaryTreeNode *pNode, int &nMaxDistance){
if (pNode == NULL)
return -1; //空节点的高度为-1
//递归
int nHeightOfLeftTree = HeightOfBinaryTree(pNode->m_pLeft, nMaxDistance) + 1; //左子树的的高度加1
int nHeightOfRightTree = HeightOfBinaryTree(pNode->m_pRight, nMaxDistance) + 1; //右子树的高度加1
int nDistance = nHeightOfLeftTree + nHeightOfRightTree; //距离等于左子树的高度加上右子树的高度+2
nMaxDistance = nMaxDistance > nDistance ? nMaxDistance : nDistance; //得到距离的最大值
return max(nHeightOfLeftTree, nHeightOfRightTree);
}
int TreeDepth(TreeNode *pRoot){
if(!pRoot) return 0;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return max(left, right)+1;
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode *left, TreeNode *right){
if(!left && !right) return true;
if(!left || !right || left->val!=right->val) return false;
return isSymmetric(left->left, right->right) &&
isSymmetric(left->right, right->left);
}
bool isSubtree(TreeNode* s, TreeNode* t) {
if (!s) return false;
if (isSame(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool isSame(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t) return false;
if (s->val != t->val) return false;
return isSame(s->left, t->left) && isSame(s->right, t->right);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root==p || root==q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
if(left && left!=p && left!=q) return left;
TreeNode *right = l
}
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return {};
stack<TreeNode*> s;
vector<int> res;
s.push(root);
while(!s.empty()){
TreeNode *p = s.top();
s.pop();
res.push_back(p->val);
if(p->right) s.push(p->right);
if(p->left) s.push(p->left);
}
return res;
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *p = root;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
vector<int> postorderTraversal(TreeNode* root) {
if(!root) return {};
stack<TreeNode*> s;
vector<int> res;
s.push(root);
while(!s.empty()){
TreeNode *cur = s.top(); s.pop();
if(cur->left) s.push(cur->left);
if(cur->right) s.push(cur->right);
res.insert(res.begin(), cur->val);
}
return res;
}
bool isBalanced(TreeNode* root) {
int depth = 0;
return isBalanced(root, depth);
}
bool isBalanced(TreeNode *root, int &depth){
if(!root) return true;
int left=0, right=0;
bool leftBalanced = isBalanced(root->left, left);
bool rightBalanced = isBalanced(root->right, right);
depth = max(left, right) + 1;
if(!leftBalanced || !rightBalanced) return false;
if(abs(left-right)>1) return false;
return true;
}
未完待续, 有时间再补充