跳题,不熟悉的留到周末再做。
保持冷静,不信画饼。
num 100 相同的树 Same Tree
做法可能不是特别简洁,注意一下。最后判断完子树以后,要确定根的数值是一样的
然后在isleaf的判定先要确定NULL
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isleaf(TreeNode*p) { if (p==NULL) return false; if(p->left==NULL && p->right==NULL) return true; else return false; } bool isSameTree(TreeNode* p, TreeNode* q) { if(isleaf(p) && isleaf(q)) { if(p->val==q->val) return true; else return false; } else { if(isleaf(p) && !isleaf(q)) return false; if(!isleaf(p) && isleaf(q)) return false; if(p==NULL && q!=NULL) return false; if(p!=NULL && q==NULL) return false; if(p==NULL && q==NULL) return true; if((p->val==q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right)) return true; else return false; } return false; } };
num 104 二叉树的最大深度 Maximum Depth of Binary Tree
注意判断root==NULL
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode* root) { if(root==NULL) return 0; if(root->left==NULL && root->right==NULL) return 1; if(root->left==NULL) return(maxDepth(root->right)+1); if(root->right==NULL) return (maxDepth(root->left)+1); else return (max(maxDepth(root->left),maxDepth(root->right))+1); } };