本文主要是介绍力扣hot100学习记录(十二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
94. 二叉树的中序遍历
给定一个二叉树的根节点 root,返回它的中序遍历。
题意
给定一个二叉树,返回它的中序遍历
思路
采用递归的思想,只要根节点不为空,则一直递归遍历左子树,然后将根节点的值存入结果,最后递归遍历右子树。
代码
class Solution {
public:vector<int> ans;vector<int> 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;}
};
这篇关于力扣hot100学习记录(十二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!