Open Ni-Guvara opened 1 year ago
直接从右往左
那我就从左往右
/**
* 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 findBottomLeftValue(TreeNode root) {
LinkedList<TreeNode> list = new LinkedList<>();
list.offer(root);
TreeNode ans = root;
while(!list.isEmpty()){
int size = list.size();
boolean flag = true;
for(int i = 0; i < size; i++){
TreeNode cur = list.poll();
if(i == 0) ans = cur;
if(cur.left != null || cur.right != null){
flag = false;
}
if(cur.left != null){
list.offer(cur.left);
}
if(cur.right != null){
list.offer(cur.right);
}
}
if(flag){
return ans.val;
}
}
return ans.val;
}
}
递归解法
/**
* 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 {
private int ans;
private int maxDepth = Integer.MIN_VALUE;
void helper(TreeNode root, int depth){
if(root.left == null && root.right == null){
if(depth > maxDepth){
maxDepth = depth;
ans = root.val;
}
}
if(root.left != null){
depth++;
helper(root.left, depth);
depth--;
}
if(root.right != null){
depth++;
helper(root.right, depth);
depth--;
}
}
public int findBottomLeftValue(TreeNode root) {
helper(root, 0);
return ans;
}
}