binary tree ab
来源:互联网 发布:js数组去重函数 编辑:程序博客网 时间:2024/05/20 23:30
1题目
二叉树中只有a,b两种值,寻找全是a或者全是b的最长路径,即a只能连a,b只能连b
例如
a
b a
b a b a
长度为3即最右路径
2、算法
利用前序dfs遍历,并维护max值以及count值,如果根结点与孩子结点值相同,则count+=1,不同count=1即从孩子结点继续向下。
3、code
struct TreeNode {
char val;
TreeNode *left;
TreeNode *right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
public:
int maxValue = 1;
int BSTab(TreeNode *root) {
if(root ==NULL)
return -1;
int count = 1;
pre_order_dfs(root,count);
return maxValue;
}
void pre_order_dfs(TreeNode *root,int count ){
if(root!=NULL){
char pre = root->val;
int key =count ;
if(root->left!=NULL){
char left = root->left->val;
if(left==pre){
count++;
maxValue = max(maxValue,count);
pre_order_dfs(root->left,count);
}
else{
count = 1;
pre_order_dfs(root->left,count);
}
}
count =key;
if(root->right!=NULL){
char right = root->right->val;
if(right==pre){
count++;
maxValue = max(maxValue,count);
pre_order_dfs(root->right,count);
}
else{
count = 1;
pre_order_dfs(root->right,count);
}
}
if(root->right==NULL&&root->left==NULL)
count = 1;
}
}
};
0 0
- binary tree ab
- Binary tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- binary tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- Binary Tree
- 哈希表与红黑树
- 寻找矩阵中最短路径 Minimum Path Sum
- generateMatrix 给定N 返回指定矩阵
- 判断幂数
- Different Ways to Add Parentheses
- binary tree ab
- URL编码的简单理解
- 特征选择专题
- linux chmod 命令
- 算法评判标准:召回率(recall)与查准率(precision)
- vim 查找
- linux 打包和压缩
- wordcount java
- Triangle