题目一
解法
/**
* 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 {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
method(root);
return root;
}
public void method(TreeNode root){
if(root==null) return;
method(root.right);
sum+=root.val;
root.val = sum;
method(root.left);
}
}
题目二
解法
/**
* 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> list = new ArrayList<Integer>();
public List<Integer> largestValues(TreeNode root) {
method(root,0);
return list;
}
public void method(TreeNode root,int depth){
if(root==null) return;
if(list.size()==depth){
list.add(Integer.MIN_VALUE);
}
if(list.get(depth)<=root.val){
list.set(depth,root.val);
}
method(root.left,depth+1);
method(root.right,depth+1);
}
}
题目三
解法
/**
* 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<List<Integer>> list = new ArrayList<List<Integer>>();
public int findBottomLeftValue(TreeNode root) {
method(root,0);
return list.get(list.size()-1).get(0);
}
public void method(TreeNode root,int depth){
if(root==null) return;
if(list.size()==depth){
list.add(new ArrayList<Integer>());
}
list.get(depth).add(root.val);
method(root.left,depth+1);
method(root.right,depth+1);
}
}