层序遍历
层序遍历也就是广度优先搜索,需要利用队列进行操作
个人感觉层序遍历的迭代法比递归法要用的舒服一点。
各自需要注意一些细节,在迭代法中,判定现有的队列长度一定要记录下来,要不在后续过程中,随着队列被添加进入下一层节点的元素,队列的长度会发生变化。
迭代法中需要同时传入层数这一个变量,然后再每一层的最开始的元素时,需要插入一个空的数组才可以,因为不知道最大层数,所以每一层最开始需要先插入一层。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
# 递归法
class Solution {
public:
void order(TreeNode* cur, vector<vector<int>>& result, int depth)
{
if (cur == nullptr) return;
if (result.size() == depth) result.push_back(vector<int>());
result[depth].push_back(cur->val);
order(cur->left, result, depth + 1);
order(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
int depth = 0;
order(root, result, depth);
return result;
}
};
111. 二叉树的最小深度
这道题就是经典的层序遍历问题,本来代码随想录中有十道题目,但是因为时间紧张,就挑了几道来做一下。
go比c++方便的一点就是可以做完一整层后把上一层的统一清除。
func minDepth(root *TreeNode) int {
h := 0
if root == nil{
return h
}
hash := make([]*TreeNode,0)
hash = append(hash, root)
for len(hash) != 0{
lenh := len(hash)
h++
for i := 0; i < lenh; i++{
if hash[i].Left == nil && hash[i].Right == nil{
return h
}
if hash[i].Left != nil{
hash = append(hash, hash[i].Left)
}
if hash[i].Right != nil{
hash = append(hash, hash[i].Right)
}
}
hash = hash[lenh:]
}
return h
}
226.翻转二叉树
这道题可以发现,其实就是将自己左右两个子节点的顺序交换,其余的不需要改变。
解题有好多种,dfs中可以从上往下遍历,也可以从下往上遍历。
bfs也可以将树的所有节点压到一个切片里,然后从头或者从末尾开始挨个转换
func invertTree(root *TreeNode) *TreeNode {
//dfs从上往下
if root != nil{
dfs(root)
}
return root
}
func dfs(node *TreeNode){
tmp := node.Left
node.Left = node.Right
node.Right = tmp
if node.Left != nil{
dfs(node.Left)
}
if node.Right != nil{
dfs(node.Right)
}
}
101.对称二叉树 2
对称二叉树 2
本题做一次忘一次,简单题也不是那么简单
使用递归的话,其实是检验内部节点和外部节点分别是否相等的问题
里面还有迭代法的思路,就是要将左侧树和右侧书分别装入两个队列进行比较,需要注意的是不能落下空节点的部分
func isSymmetric(root *TreeNode) bool {
if root != nil{
return compare((*root).Left, (*root).Right)
}
return true
}
func compare(left , right *TreeNode) bool{
if left == nil && right != nil {
return false
}
if left != nil && right == nil {return false}
if left == nil && right == nil {return true}
if (*left).Val != (*right).Val {return false}
out := compare((*left).Left, (*right).Right)
in := compare((*left).Right, (*right).Left)
return out && in
}