平衡二叉树
考研的时候我记得这个平衡二叉树的题做过,用的方法是DFS; 自底向上后序遍历去计算每个结点的高度,指向NULL的空结点高度默认为0,定义一个flag标志位默认为true,若出现了左右子树的高度差的绝对值超过了1,那么置flag为false,代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool flags = true;
bool isBalanced(TreeNode* root) {
DFS(root,flags);
return flags;
}
int DFS(TreeNode* root, bool &flags){
if(flags == false || root == NULL)
return 0;
int left_h = DFS(root->left,flags);
int right_h = DFS(root->right,flags);
if(abs(left_h-right_h)>1)
flags = false;
//cout<<"left = "<<left_h<<" right = "<<right_h<<" root_h = "<<max(left_h,right_h)+1<<endl;
return max(left_h,right_h)+1;
}
};

图像渲染
也是典型的DFS,要注意的是,对于边界条件的判断,因为有可能会超到图片外面去,所以需要在条件判断的时候对坐标的位置进行合法性判断; 而且已经判断过的像素位置不可以再进入DFS,因此需要去排除掉那些已经DFS遍历过的像素,方法是将已进入过DFS且符合像素值与value相等的像素指改为-1(相当于标记为已访问),这样后面再去判断像素值是否相等的时候,就会排除掉它;
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
vector<int> sr_list;
vector<int> sc_list;
int value = image[sr][sc];
DFS(sr,sc,sr_list,sc_list,image,value);
for(int i=0;i<sr_list.size();i++)
image[sr_list[i]][sc_list[i]] = newColor;
return image;
}
void DFS(int sr, int sc, vector<int> &sr_list, vector<int> &sc_list, vector<vector<int>> image, int value){
if(sr<0 || sr>=image.size() || sc<0 || sc>=image[0].size() || image[sr][sc]!= value)
return;
image[sr][sc] = -1;
sr_list.push_back(sr);
sc_list.push_back(sc);
DFS(sr-1,sc,sr_list,sc_list,image,value);
DFS(sr+1,sc,sr_list,sc_list,image,value);
DFS(sr,sc-1,sr_list,sc_list,image,value);
DFS(sr,sc+1,sr_list,sc_list,image,value);
}
};
本文深入探讨了平衡二叉树的判定方法,采用深度优先搜索(DFS)实现,通过自底向上后序遍历计算节点高度,确保树的平衡性。同时,介绍了图像渲染中的DFS应用,通过有效边界条件判断和像素访问标记,实现区域填充算法。

被折叠的 条评论
为什么被折叠?



