1--二叉树的层序遍历(102)
主要思路:
经典广度优先搜索,基于队列;
对于本题需要将同一层的节点放在一个数组中,因此遍历的时候需要用一个变量 nums 来记录当前层的节点数,即 nums 等于队列元素的数目;
#include <iostream>
#include <vector>
#include <queue>struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};class Solution {
public:std::vector<std::vector<int>> levelOrder(TreeNode* root) {std::vector<std::vector<int>> res;if(root == nullptr) return res;std::queue<TreeNode*> q;q.push(root);while(!q.empty()){int nums = q.size(); // 当前层的节点数std::vector<int> tmp;while(nums > 0){ // 遍历处理同一层TreeNode *cur = q.front();q.pop();tmp.push_back(cur->val);if(cur->left != nullptr) q.push(cur->left);if(cur->right != nullptr) q.push(cur->right);nums--;}res.push_back(tmp); // 记录当前层的元素}return res;}
};int main(int argc, char* argv[]){// root = [1, null, 2, 3]TreeNode *Node1 = new TreeNode(3);TreeNode *Node2 = new TreeNode(9);TreeNode *Node3 = new TreeNode(20);TreeNode *Node4 = new TreeNode(15);TreeNode *Node5 = new TreeNode(7);Node1->left = Node2;Node1->right = Node3;Node3->left = Node4;Node3->right = Node5;Solution S1;std::vector<std::vector<int>> res = S1.levelOrder(Node1);for(auto item : res) {for (int v : item) std::cout << v << " ";std::cout << std::endl;}return 0;
}
2--二叉树的最大深度
主要思路:
递归计算左右子树的深度,选取两者最大值 +1 返回;
#include <iostream>
#include <vector>
#include <queue>struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};class Solution {
public:int maxDepth(TreeNode* root) {if(root == nullptr) return 0;int res = dfs(root);return res;}int dfs(TreeNode* root){if(root == nullptr) return 0;int left_height = dfs(root->left);int right_height = dfs(root->right);int cur_height = std::max(left_height, right_height) + 1;return cur_height;}
};int main(int argc, char* argv[]){// root = [3,9,20,null,null,15,7]TreeNode *Node1 = new TreeNode(3);TreeNode *Node2 = new TreeNode(9);TreeNode *Node3 = new TreeNode(20);TreeNode *Node4 = new TreeNode(15);TreeNode *Node5 = new TreeNode(7);Node1->left = Node2;Node1->right = Node3;Node3->left = Node4;Node3->right = Node5;Solution S1;int res = S1.maxDepth(Node1);std::cout << res << std::endl;return 0;
}
3--从前序与中序遍历序列构造二叉树
主要思路: