使用记录遍历到的节点的高度,curVal 记录高度在curHeight 的最左节点的值。在深度优先搜索时,我们先搜索当前节点的左子节点,再搜索当前节点的右子节点,然后判断当前节点的高度 height 是否大于 curHeight,如果是,那么将 curVal 设置为当前结点的值,curHeight 设置为 height。
- class Solution {
- int curval=0;
- int curheight=0;
- public int findBottomLeftValue(TreeNode root) {
- int curheight=0;
- dfs(root,0);
- return curval;
- }
- public void dfs(TreeNode root,int height){
- if(root==null){
- return ;
- }
- height++;
- dfs(root.left,height);
- dfs(root.right,height);
- if(height>curheight){
- curheight=height;
- curval=root.val;
- }
- }
- }
思想是加入队列 先让右端点进队列 总能够尽量在队尾剩下左端点
然后依次遍历 赋值
- class Solution {
- public int findBottomLeftValue(TreeNode root) {
- int ret=0;
- Queue<TreeNode> Queue=new ArrayDeque<TreeNode>();
- Queue.offer(root);
- while(!Queue.isEmpty()){
- TreeNode p=Queue.poll();
- if(p.right!=null){
- Queue.offer(p.right);
- }
- if(p.left!=null){
- Queue.offer(p.left);
- }
- ret=p.val;
- }
- return ret;
- }
-
- }