104. 二叉树的最大深度
class Solution { public: int maxDepth(TreeNode* root) { if(root==NULL)return 0; return 1+max(maxDepth(root->left),maxDepth(root->right)); } };
559. N 叉树的最大深度
class Solution { public: int maxDepth(Node* root) { if(root==NULL)return 0; int depth=0; for(int i=0;i<root->children.size();i++){ depth=max(depth,maxDepth(root->children[i])); } return depth+1; } };
111. 二叉树的最小深度
class Solution { public: int minDepth(TreeNode* root) { if(root==NULL)return 0; if(root->left==NULL&&root->right)return 1+minDepth(root->right); else if(root->right==NULL&&root->left)return 1+minDepth(root->left); else return 1+min(minDepth(root->left),minDepth(root->right)); } };
222. 完全二叉树的节点个数
当成普通二叉树来求,下面我用前序遍历法,还可用左右中的后序遍历法、
class Solution { public: int count=0; int countNodes(TreeNode* root) { if(root==NULL)return 0; count++; countNodes(root->left); countNodes(root->right); return count; } };
当成完全二叉树来求,算法时间复杂度更优一些
class Solution { public: int countNodes(TreeNode* root) { if (root == nullptr) return 0; TreeNode* left = root->left; TreeNode* right = root->right; int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便 while (left) { // 求左子树深度 left = left->left; leftDepth++; } while (right) { // 求右子树深度 right = right->right; rightDepth++; } if (leftDepth == rightDepth) { return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0 } return countNodes(root->left) + countNodes(root->right) + 1; } };
标签:right,return,int,随想录,二叉树,深度,root,left From: https://www.cnblogs.com/zhishikele/p/17048377.html