题目一
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
method(root1,list1);
method(root2,list2);
if(list1.size()==list2.size()){
for(int i = 0;i<list1.size();i++){
if(list1.get(i)!=list2.get(i)){
return false;
}
}
return true;
}else{
return false;
}
}
public void method(TreeNode root,List list){
if(root==null) return;
if(root.left==null&&root.right==null) list.add(root.val);
method(root.left,list);
method(root.right,list);
}
}
题目二
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
return method(root,low,high);
}
public int method(TreeNode root, int low, int high){
if(root==null) return 0;
if(root.val<low) return method(root.right,low,high);
if(root.val>high) return method(root.left,low,high);
return root.val+method(root.left,low,high)+method(root.right,low,high);
}
}
题目三
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isUnivalTree(TreeNode root) {
if(root==null) return true;
if(root.left!=null){
if(root.val!=root.left.val) return false;
}
if(root.right!=null){
if(root.val!=root.right.val) return false;
}
return isUnivalTree(root.left)&&isUnivalTree(root.right);
}
}
题目四
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
HashSet<Integer> set = new HashSet<Integer>();
int ans = 0;
public int numColor(TreeNode root) {
method(root);
return ans;
}
public void method(TreeNode root){
if(root==null) return;
if(!set.add(root.val)){
}else{
set.add(root.val);
ans++;
}
method(root.left);
method(root.right);
}
}