513. Find Bottom Left Tree Value

来源:互联网 发布:goodtv网络电视台直播 编辑:程序博客网 时间:2024/06/03 23:43

题目:找出二叉树最后一层,最左边的孩子,返回该节点的值

  /*    解题思路:采用层次遍历,用一个nlast指向每一层中最右边的孩子,last一开始指向根节点,当出队列的节点temp=last的时候,             更新last的值为nlast,用result表示每一次最左边的孩子,当last==temp的时候,更新result的值为下一次出队列的节点,             为了方便,设置一个flage变量,当flage的值为true的时候,result==temp;    */    public int findBottomLeftValue(TreeNode root) {        LinkedList<TreeNode> list=new LinkedList<TreeNode>();        list.add(root);        TreeNode last=root;        TreeNode nlast=null;        boolean flage=false;        TreeNode result=root;       /* if(root.left==null&&root.right==null){            return root.val;        }*/        while(list.size()!=0){            TreeNode temp=list.remove();            if(flage){                result=temp;            }            if(temp.left!=null){                list.add(temp.left);                nlast=temp.left;            }            if(temp.right!=null){                list.add(temp.right);                nlast=temp.right;            }            if(temp==last){//这一层遍历结束                last=nlast;                flage=true;                continue;//这个很重要            }            if(temp!=last){                flage=false;            }        }//while        return result.val;    }