二叉树part01(二)
今天都是二叉树的基础题
1. 翻转二叉树
void dfs(TreeNode* root) {if (root==NULL) return;swap(root->left, root->right);dfs(root->left);dfs(root->right);
}TreeNode* invertTree(TreeNode* root) {if (root == NULL) return root;// 交换左右孩子即可dfs(root);return root; }
2. 对称二叉树
class Solution {
public:bool sym(TreeNode* left, TreeNode* right){ if (left == NULL && right == NULL) return true; // 左右都为空对称// 左右缺一不对称else if (left == NULL && right != NULL) return false; else if (left != NULL && right == NULL) return false;// 左右不缺值不等不对称else if (left->val != right->val) return false;// 因为是轴对称,左对右,右对左bool left_ = sym(left->left, right->right);bool right_ = sym(left->right, right->left);return left_&&right_;}bool isSymmetric(TreeNode* root) {if (root == NULL) return true;return sym(root->left, root->right);}
};
3. 二叉树的最大深度
前序遍历求深度(自上而下深度递增),如果是根节点的高度(自上而下高度递减),所以本题用前序遍历很方便
int res = 0;void dfs(TreeNode* root, int depth) {res = max(depth,res);if(root->left) dfs(root->left, depth+1);if(root->right) dfs(root->right, depth+1);return;}int maxDepth(TreeNode* root) {if (root == NULL) return res;dfs(root, 1);return res;}
3. 二叉树的最小深度
主要要确保找到的最小深度是叶子节点的最小深度
int ord(TreeNode* root) {if (root == NULL) return 0;int l = ord(root->left);int r = ord(root->right);// 确保找到的是叶子节点if (l == 0 && r != 0) return 1 + r;if (r == 0 && l != 0) return 1 + l;return 1 + min(l, r);}int minDepth(TreeNode* root) {return ord(root);}