513.找树左下角的值
力扣题目链接(opens new window)
给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
示例 2:
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 {public int findBottomLeftValue(TreeNode root) {Queue<TreeNode>que = new LinkedList<TreeNode>();que.offer(root);int res = 0;while(!que.isEmpty()){//遍历每一层int len = que.size();//用于记录每一层节点的个数// int s= len;boolean firstNodeInLevel = true;while(len>0){//对每一层数据进行处理TreeNode t = que.poll();if(firstNodeInLevel){res = t.val;firstNodeInLevel = false;}if(t.left!=null) que.offer(t.left);if(t.right!=null) que.offer(t.right);len--;}}return res;}
}
2,递归
思考,在递归下便跟一个回溯,这是因为你一直递归到叶节点,然后回退的时候就要把深度减回来,如果不回溯(也就是depth--),那么你遍历完左子树,再去遍历右子树,它的深度是在原先的基础上加加。 (有点绕,回头再来补)
/*** 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 maxdepth = -1;//全局变量maxdepthint res;//全局变量void traversal(TreeNode root,int depth){if(root.left==null&&root.right==null){//递归终止条件if(depth>maxdepth){//遇到叶子节点时,要统计更新最大深度maxdepth = depth;res = root.val;}return;}if(root.left!=null){//左优先!depth++;traversal(root.left,depth);depth--;//回溯,就是你在退回到某个节点的所在层时,还是原来的深度,要不然就一直++,这样不对}if(root.right!=null){depth++;traversal(root.right,depth);depth--;//回溯}return;}public int findBottomLeftValue(TreeNode root) {traversal(root,0);return res;}
}