题目一
解法
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null) return null;
TreeNode node = new TreeNode(root.val);
node.left = mirrorTree(root.right);
node.right = mirrorTree(root.left);
return node;
}
}
题目二
?解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
method(0,root);
return res;
}
public void method(int depth, TreeNode root){
if(root==null) return;
if (res.size() == depth) {
res.add(new ArrayList<Integer>());
}
res.get(depth).add(root.val);
method(depth+1,root.left);
method(depth+1,root.right);
}
}
题目三
?解法一
/**
* 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 {
ArrayList<Double> list = new ArrayList<Double>();
ArrayList<List<Integer>> temp = new ArrayList<List<Integer>>();
public List<Double> averageOfLevels(TreeNode root) {
method(0,root);
Double cont = 0.0;
for(int i = 0;i<temp.size();i++){
for(int j =0;j<temp.get(i).size();j++){
cont+=temp.get(i).get(j);
}
Double d = cont/temp.get(i).size();
list.add(d);
cont = 0.0;
}
return list;
}
public void method(int depth,TreeNode root){
if(root==null) return;
if(temp.size()==depth){
temp.add(new ArrayList<Integer>());
}
temp.get(depth).add(root.val);
method(depth+1,root.left);
method(depth+1,root.right);
}
}
题目四
?解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<Integer>();
public int kthLargest(TreeNode root, int k) {
method(root);
return list.get(list.size()-k);
}
public void method(TreeNode root){
if(root==null) return;
method(root.left);
list.add(root.val);
method(root.right);
}
}
|