统计唯一值子树个数——lintcode921/leetcode250
统计唯一值子树个数
题目:统计唯一值子树个数
给定一棵二叉树,统计唯一值子树的数目.唯一值子树意味着子树的所有节点都具有相同的值.
示例:
输入: root = {5,1,5,5,5,#,5}
输出: 4
解释:
5
/ \
1 5
/ \ \
5 5 5
题解
1. BFS+DFS
BFS遍历每个节点,DFS判断每个节点是否正确。(时间效率不高,懒人法)
public class Solution {
private int sum;
//dfs判断是否是同值子树
public boolean dfs(TreeNode root, int key) {
if (root == null) return true;
if (root.val != key) return false;
return dfs(root.left, key) && dfs(root.right, key);
}
public int countUnivalSubtrees(TreeNode root) {
sum = 0;
if (root == null) return sum;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
//bfs遍历二叉树
while (!queue.isEmpty()) {
TreeNode temp = queue.poll();
if (dfs(temp, temp.val)) sum++;
if (temp.left != null) queue.add(temp.left);
if (temp.right != null) queue.add(temp.right);
}
return sum;
}
}
2. DFS判断每个节点
public class Solution2 {
private int sum;
public boolean dfs(TreeNode root) {
if (root == null) return true;
boolean left = dfs(root.left);
boolean right = dfs(root.right);
if (left && right) {
if ((root.left != null && root.left.val != root.val) || (root.right != null && root.right.val != root.val)) {
return false;
}
sum++;
return true;
}
return false;
}
public int countUnivalSubtrees(TreeNode root) {
sum = 0;
dfs(root);
return sum;
}
}