思路
求的是左下角的值,不是左叶子节点。直接用层序遍历就行。
代码
/**
* 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) {
if(root == null){
return 0;
}
Queue<TreeNode>queue = new LinkedList<>();
queue.add(root);
LinkedList<TreeNode> res = new LinkedList<>();
while(!queue.isEmpty()){
int length =queue.size();
for(int i = 0;i<length;i++){
TreeNode temp = queue.poll();
res.add(temp);
if(temp.right != null)
queue.add(temp.right);
if(temp.left != null)
queue.add(temp.left);
}
}
return res.get(res.size()-1).val;
}
}
|