二叉树前序是在进入一个节点的时候进行计算,而后序是离开节点的时候进行计算;
所以前序是自上而下计算的,后序是自下而上的计算
Leetcode 104
1.后序遍历(分解问题)
后序遍历可以得到子树的数据,相当于离开某一节点(此时已经遍历完它子树的所有节点)再做计算
class Solution {
public:
int GetDepth(TreeNode* root){
if(root == NULL) return 0;
int leftDepth = GetDepth(root->left);
int rightDepth = GetDepth(root->right);
int maxVal = 1 + max(leftDepth, rightDepth);
return maxVal;
}
int maxDepth(TreeNode* root) {
int max = GetDepth(root);
return max;
}
};
这里,计算maxVal的时候,函数已经遍历了curr节点下所有的左右子树
2.前序遍历(回溯?)
class Solution {
public:
int res;
int depth;
void GetDepth(TreeNode* root){
if(root == NULL) return;
depth++;
res = max(depth, res);
GetDepth(root->left);
GetDepth(root->right);
depth--;
}
int maxDepth(TreeNode* root) {
GetDepth(root);
return res;
}
};
这里需要注意的是,再最后需要depth--,这是因为此时完成了一条分支的计算,需要返回上一个节点,所以深度需要-1
3.层序遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
int depth = 0;
if(root != NULL) que.push(root);
while(!que.empty()){
int size = que.size();
for(int i=0; i<size; i++){
TreeNode* curr = que.front();
que.pop();
if(curr->left) que.push(curr->left);
if(curr->right) que.push(curr->right);
}
depth++;
}
return depth;
}
};
559. Maximum Depth of N-ary Tree
111. Minimum Depth of Binary Tree
这里要注意的是,只有两边都没有子叶了才是leaf
1.层序
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
if(root != NULL) que.push(root);
int depth = 0;
while(!que.empty()){
int size = que.size();
depth++;
for(int i=0; i<size; i++){
TreeNode* curr = que.front();
que.pop();
if(curr->left) que.push(curr->left);
if(curr->right) que.push(curr->right);
if(curr->left == NULL && curr->right == NULL) return depth;
}
}
return depth;
}
};
2.递归(感觉不是特别熟,之后要再看看)
class Solution {
public:
int getDepth(TreeNode* root) {
if(root == NULL) return 0;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if(root->right != NULL && root->left == NULL){
return ++rightDepth;
}if(root->left != NULL && root->right == NULL){
return ++leftDepth;
}
int minDepth = 1+min(leftDepth, rightDepth);
return minDepth;
}
int minDepth(TreeNode* root){
return getDepth(root);
}
};
222. Count Complete Tree Nodes
首先要看到的是这是一个完全二叉树,我们要利用完全二叉树的特点降低时间复杂度
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int lh=1, rh =1;
while(left){
left = left->left;
lh++;
}
while(right){
right = right->right;
rh++;
}
if(lh == rh){
return pow(2,lh) - 1;
}
return 1+countNodes(root->left) + countNodes(root->right);
}
};
为什么要利用公式呢?
因为这是一个完全二叉树,其左右子叶一定有一个是完全二叉树,这就意味着时间复杂度由N *logN减少为了logN*logN
734

被折叠的 条评论
为什么被折叠?



