leetcode 每日一题 513. 找树左下角的值

leetcode 每日一题 513. 找树左下角的值

/**
 * 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 num = 0;
    private int height = -1;
    public int findBottomLeftValue(TreeNode root) {
        //遍历二叉树
        f(root,0);
        return num;
    }

    /**
     * @Author xzj
     * @Description //TODO
     * @Date 9:40 2022/6/22
     * @param root 节点
     * @param i 层高
     * @return
     **/
    private void f(TreeNode root, int i) {
        if(root == null){
            return;
        }
        if(i > height){
            num = root.val;
            height = i;
        }
        f(root.left,i+1);
        f(root.right,i+1);
    }
}

var height int
var num int
func findBottomLeftValue(root *TreeNode) int {
    height = -1
    num = 0
    dfs(root,0)
    return num
}
func dfs(root *TreeNode,i int) {
    if root == nil {
        return
    }
    //层高更高
    if i > height{
        height = i
        num = root.Val
    }
    dfs(root.Left,i+1)
    dfs(root.Right,i+1)
}

 

posted @ 2022-06-22 10:46  java架构师1  阅读(22)  评论(0)    收藏  举报