成都建设网站建设,动力无限做网站,公共交易中心资源网,网站建设制作需要多少钱94. 二叉树的中序遍历
给定一个二叉树的根节点 root#xff0c;返回它的中序遍历。 题意 给定一个二叉树#xff0c;返回它的中序遍历 思路 采用递归的思想#xff0c;只要根节点不为空#xff0c;则一直递归遍历左子树#xff0c;然后将根节点的值存入结果#xff0c;…94. 二叉树的中序遍历
给定一个二叉树的根节点 root返回它的中序遍历。 题意 给定一个二叉树返回它的中序遍历 思路 采用递归的思想只要根节点不为空则一直递归遍历左子树然后将根节点的值存入结果最后递归遍历右子树。 代码
class Solution {
public:vectorint ans;vectorint inorderTraversal(TreeNode* root) {dfs(root);return ans;}void dfs(TreeNode* root){if(!root) return;dfs(root-left);ans.push_back(root-val);dfs(root-right);}
};104. 二叉树的最大深度
给定一个二叉树 root 返回其最大深度。 二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。 题意 给定一个二叉树返回二叉树的最大深度 思路 利用dfs遍历当节点不为空时遍历其左子树和右子树每次的结果为左子树的最大长度和右子树的最大长度的最大值加1 代码
class Solution {
public:int maxDepth(TreeNode* root) {if(!root) return 0;return max(maxDepth(root-left),maxDepth(root-right)) 1;}
};226. 翻转二叉树
给你一棵二叉树的根节点 root 翻转这棵二叉树并返回其根节点。
题意 将二叉树沿着根节点翻转 思路 先将根节点的两棵子树交换在将两棵子树翻转 代码
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(!root) return NULL;swap(root-left, root-right);invertTree(root-left);invertTree(root-right);return root;}
};