## 104.二叉树的最大深度
代码
class Solution { public: void travel(TreeNode* cur,int& result,int& temp){ temp++; if(cur == nullptr) return; if(temp>result) result = temp; travel(cur->left,result,temp); temp--; travel(cur->right,result,temp); temp--; } int maxDepth(TreeNode* root) { int result = 0,temp=0; travel(root,result,temp); return result; } };
示例代码:后序遍历
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); } };
示例代码:前序遍历
class Solution { public: int result; void getdepth(TreeNode* node, int depth) { result = depth > result ? depth : result; // 中 if (node->left == NULL && node->right == NULL) return ; if (node->left) { // 左 depth++; // 深度+1 getdepth(node->left, depth); depth--; // 回溯,深度-1 } if (node->right) { // 右 depth++; // 深度+1 getdepth(node->right, depth); depth--; // 回溯,深度-1 } return ; } int maxDepth(TreeNode* root) { result = 0; if (root == NULL) return result; getdepth(root, 1); return result; } };
思路
本题我采用了前序遍历的解题思路,不过示例代码中的后序遍历对递归的运用也非常巧妙
111.二叉树的最小深度
代码
class Solution { public: void travel(TreeNode* cur, int& result, int& temp) { temp++; if (cur == nullptr) return; if (cur->left == nullptr && cur->right == nullptr) if (temp < result) result = temp; travel(cur->left, result, temp); temp--; travel(cur->right, result, temp); temp--; } int minDepth(TreeNode* root) { if(root == nullptr) return 0; int result = 100000, temp = 0; travel(root, result, temp); return result; } };
示例代码
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; } // 当一个右子树为空,左不为空,这时并不是最低点 if (node->left != NULL && node->right == NULL) { return 1 + leftDepth; } int result = 1 + min(leftDepth, rightDepth); return result; } int minDepth(TreeNode* root) { return getDepth(root); } };
思路
在上一题的代码上稍作了修改
222.完全二叉树的节点个数
代码
示例代码
class Solution { public: int travel(TreeNode* cur){ if(cur==nullptr) return 0; int left = travel(cur->left); int right = travel(cur->right); return left+right+1; } int countNodes(TreeNode* root) { return travel(root); } };
思路
使用后序遍历,用简洁的代码做出本题