代码训练day16二叉树p4

1.找树左下角的值

(1)bfs层序遍历技巧先右入队再左入队,最后出来的是左下角

class Solution {
    // bfs 实现 先右儿子入队,再左孩子入队。最后一个出队节点为左下角节点
    public int findBottomLeftValue(TreeNode root) {
        Deque que = new ArrayDeque<>();
        TreeNode node = root;
        que.offer(root);
        while (!que.isEmpty()) {
            int levelsize = que.size();
            for (int i = 0; i < levelsize; i++) {
                node = que.poll();
                if (node.right != null) que.offer(node.right);
                if (node.left != null) que.offer(node.left);

            }
        }
        return node.val;
    }
}

(2)dfs实现,先找到最大深度(最后一层),在找左下角 

class Solution {
    // bfs 实现 先右儿子入队,再左孩子入队。最后一个出队节点为左下角节点
    int maxdepth = Integer.MIN_VALUE;
    int res = 0;
    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 0);
        return res;
    }
    private  void dfs(TreeNode root, int depth){
        if (root == null) return;
        // 到叶子节点终止,获得最大深度,递归停止逻辑
        if (root.left == null && root.right == null) {
            if (depth > maxdepth) {
                maxdepth = depth;
                res = root.val;
            }
        return;
        }
        // 单层递归逻辑,对左右子树递归
        if (root.left != null) {
            dfs(root.left, depth + 1);
        }
        if (root.right != null) {
            dfs(root.right, depth + 1);
        }
        return;
    }
        
}

2.路径总和

dfs每次递归减去节点值,递归到叶子节点,如果结果为0返回true

class Solution {
    // dfs每次递归减去节点值,递归到叶子节点,如果结果为0返回true
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        targetSum = targetSum - root.val;
        if (root.left == null && root.right == null) {//递归停止条件
            return targetSum == 0;
        }
        // 单层递归逻辑,对左右子树判断
        return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
    }
}

3.从中序遍历与后序遍历序列构造二叉树

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = postorder.length;
        if (n == 0) return null;
        // 先找到根节点
        int rootValue = postorder[postorder.length - 1];
        TreeNode root = new TreeNode(rootValue);
        // 根据中序遍历确定左右子树大小
        int leftsize = indexOf(inorder, postorder[n - 1]);
        int[] in1 = Arrays.copyOfRange(inorder, 0, leftsize);
        int[] in2 = Arrays.copyOfRange(inorder, leftsize + 1, n);
        int[] post1 = Arrays.copyOfRange(postorder, 0, leftsize);
        int[] post2 = Arrays.copyOfRange(postorder, leftsize, n - 1);
        // 递归逻辑
        TreeNode left = buildTree(in1, post1);
        TreeNode right = buildTree(in2, post2);
        return new TreeNode(postorder[n - 1], left, right);
    }

    private int indexOf(int[] a, int x) {// 返回索引
        for (int i = 0; ; i++) {
            if (a[i] == x)
            return i;
        }
    }
}

你可能感兴趣的:(java,数据结构,算法)