Leetcode 104. 二叉树的最大深度
思路:采用后序遍历法,记录遍历到的节点的高度,二叉树的最大深度即为根节点的高度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* node){
if(node==NULL)return 0;
int leftDepth=getDepth(node->left); //左
int rightDepth=getDepth(node->right); //右
int depth=1+max(leftDepth,rightDepth); //中
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
Leetcode 559. N 叉树的最大深度
思路:与求二叉树的最大深度思路是一样的,也是后序遍历,求出根节点的高度
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int getDepth(Node* node){
if(node==NULL)return 0;
int depth = 0;
for(int i=0;i<node->children.size();i++){
depth=max(depth,getDepth(node->children[i]));
}
int maxDepth=1+depth;
return maxDepth;
}
int maxDepth(Node* root) {
return getDepth(root);
}
};
Leetcode 111. 二叉树的最小深度
思路:与求二叉树的最大深度不同的一点是,要判断左右子树是否为空,比如左子树为空,那么即为求右子树中的最小深度。其他地方思路与求二叉树的最大深度思路一样
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* node){
if(node==NULL)return 0;
int leftDepth=getDepth(node->left); //左
int rightDepth=getDepth(node->right); //右
if(node->left==NULL && node->right != NULL)return 1+rightDepth; //中
else if(node->right==NULL && node->left != NULL)return 1+leftDepth;
return 1+min(leftDepth,rightDepth);
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
Leetcode 222. 完全二叉树的节点个数
思路:利用完全二叉树的特性,递归到某一深度的左孩子和有孩子一定有一个为满二叉树。遍历树的时候判断子树是否为满二叉树,如果为满二叉树就记录满二叉树的节点数量,最后将左右子树节点数相加,即为完全二叉树的节点树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL)return 0;
TreeNode* left=root->left;
TreeNode* right=root->right;
int leftDepth=0,rightDepth=0; //记录左右子树深度
while(left){ //得到左子树深度
left=left->left;
leftDepth++;
}
while(right){ //得到右子树深度
right=right->right;
rightDepth++;
}
if(leftDepth==rightDepth)return (2<<leftDepth)-1; //相当于2^(leftDepth+1)-1
return countNodes(root->left)+countNodes(root->right)+1; //左右子树节点数量加根节点
}
};