leetcode:513. 找树左下角的值 – 力扣(LeetCode)

思路:是找最深左下角的值,不是找左节点最深的值!!遍历深度,判断最大深度,存储后再与下一个相同深度的比较,先左后右,也就是从左到右的顺序来判断的,所以能找到树下左下角的值

class Solution {
     int maxdepth = 0;
     int result = 0;
    public int findBottomLeftValue(TreeNode root) {
        result =root.val;
        getmaxleft(root ,maxdepth);
        return result;
    }

    private void getmaxleft(TreeNode root, int depth) {

        if( root == null) return;
        //终止条件
        if( root.left == null && root.right == null){
            //判断是不是最深叶子节点
            if(depth > maxdepth){
                maxdepth = depth;
                result = root.val;
            }
        }
        //判断下一层左节点
        if(root.left != null){
            depth++;
            //回溯
            getmaxleft(root.left,depth);
            depth--;
        }
        //判断下一层右节点
        if(root.right != null){
            depth++;
            //回溯
            getmaxleft(root.right,depth);
            depth--;
        }
    }
}

 leetcode:112. 路径总和 – 力扣(LeetCode)

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        int count = targetSum;
        return counttreepath(root,count - root.val);
    }

    private boolean counttreepath(TreeNode root, int count) {

        if(root.left == null && root.right == null && count == 0) return true;
        if(root.left == null && root.right == null) return  false;
        if(root.left != null){
            count-= root.left.val;
            //回溯
            if(counttreepath(root.left,count)) return true;
            count+= root.left.val;
        }
        if(root.right != null){
            count-= root.right.val;
            //回溯
            if(counttreepath(root.right,count)) return true;
            count+= root.right.val;
        }
        return false;

    }
}

 leetcode:106. 从中序与后序遍历序列构造二叉树 – 力扣(LeetCode)

真不会啊哥

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。