【代码随想录|刷题记录Day18】513.找树左下角的值、112.路径总和、106.从中序和后序遍历序列构造二叉树

47 阅读3分钟

题目列表

  513.找树左下角的值

  112.路径总和

  113.路径总和II

  105.从前序和中序遍历序列构造二叉树

  106.从中序和后序遍历序列构造二叉树

解题过程

1、513.找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

思路: 如果使用递归法,就是要找深度最大的叶子节点;如果使用迭代法,层序遍历最合适,记录最后一层第一个节点的值就行。

递归法

class Solution {
    public int result = 0;
    public int maxDepth = -1;

    public int findBottomLeftValue(TreeNode root) {
        result = root.val;
        traversal(root, 0);
        return result;
    }

    public void traversal(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (depth > maxDepth) {
                maxDepth = depth;
                result = root.val;
            }
            return;
        }
        if (root.left != null) {
            traversal(root.left, depth + 1);
        }
        if (root.right != null) {
            traversal(root.right, depth + 1);
        }
    }
}

迭代法

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        int result = root.val;
        int maxDepth = -1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == 0) {
                    result = node.val;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return result;
    }
}

2、112.路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false

叶子节点 是指没有子节点的节点。

思路: 到叶子结点时,进行判断。

递归法

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        //叶子结点
        if (root.left == null && root.right == null) {
            return targetSum == root.val;
        }
        if (root.left != null) {
            boolean left = hasPathSum(root.left, targetSum - root.val);
            if (left) {
                return true;
            }
        }
        if (root.right != null) {
            boolean right = hasPathSum(root.right, targetSum - root.val);
            if (right) {
                return true;
            }
        }
        return false;
    }
}

迭代法

class solution {
    public boolean haspathsum(treenode root, int targetsum) {
        if(root == null) return false;
        stack<treenode> stack1 = new stack<>();
        stack<integer> stack2 = new stack<>();
        stack1.push(root);
        stack2.push(root.val);
        while(!stack1.isempty()) {
            int size = stack1.size();

            for(int i = 0; i < size; i++) {
                treenode node = stack1.pop();
                int sum = stack2.pop();

                // 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
                if(node.left == null && node.right == null && sum == targetsum) {
                    return true;
                }
                // 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
                if(node.right != null){
                    stack1.push(node.right);
                    stack2.push(sum + node.right.val);
                }
                // 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
                if(node.left != null) {
                    stack1.push(node.left);
                    stack2.push(sum + node.left.val);
                }
            }
        }
        return false;
    }
}

3、113.路径总和II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

思路: 结合了上一题有目标值的路径和二叉树所有路径那道题,只是在到达叶子结点时增加判断条件,以及带着目标值targetSum进行遍历。

递归法1

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        //最终返回的结果
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        //一条路径
        List<Integer> path = new ArrayList<>();
        traversal(root, targetSum, res, path);
        return res;
    }

    public void traversal(TreeNode root, int targetSum, List<List<Integer>>  res, List<Integer> path) {
        path.add(root.val);
        //当前节点为叶子节点,记录一条结果
        if (root.left == null && root.right == null) {
            if (targetSum - root.val == 0) {
                res.add(new ArrayList<>(path)); //直接从path中提取
            }
            return;
        }
        //处理左孩子
        if (root.left != null) {
            traversal(root.left, targetSum - root.val, res, path);
            path.remove(path.size() - 1);
        }
        //处理右孩子
        if (root.right != null) {
            traversal(root.right, targetSum - root.val, res, path);
            path.remove(path.size() - 1);
        }
    }
}

递归法2

class Solution {
    List<List<Integer>> result;
    LinkedList<Integer> path;
    public List<List<Integer>> pathSum (TreeNode root,int targetSum) {
        result = new LinkedList<>();
        path = new LinkedList<>();
        travesal(root, targetSum);
        return result;
    }
    private void travesal(TreeNode root,  int count) {
        if (root == null) return;
        path.offer(root.val);
        count -= root.val;
        if (root.left == null && root.right == null && count == 0) {
            result.add(new LinkedList<>(path));
        }
        travesal(root.left, count);
        travesal(root.right, count);
        path.removeLast(); // 回溯
    }
}

4、105.从前序和中序遍历序列构造二叉树

给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这棵二叉树。

思路: 后序序列最后一个节点一定是该棵树/子树的根节点,改节点在中序序列中的位置可以用来划分左右子树。

递归法

class Solution {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //hashmap保存中序序列的元素数值对应位置
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return findNode(inorder, 0, inorder.length, preorder, 0, preorder.length);
    }

    public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] preorder, int preBegin, int preEnd) {
        if (inBegin >= inEnd || preBegin >= preEnd) {
            return null;
        }
        //找到前序遍历第一个元素在中序序列中的位置
        int rootIndex = map.get(preorder[preBegin]);
        //构造根节点
        TreeNode root = new TreeNode(inorder[rootIndex]);
        //保存中序左子树的个数,用来确定前序序列的个数
        int lenOfLeft = rootIndex - inBegin;
        //构造左子树
        root.left = findNode(inorder, inBegin, rootIndex, preorder, preBegin + 1, preBegin + lenOfLeft + 1);
        //构造右子树
        root.right = findNode(inorder, rootIndex + 1, inEnd, preorder, preBegin + lenOfLeft + 1, preEnd);
        return root;
    }
}

5、106.从中序和后序遍历序列构造二叉树

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

递归法

class Solution {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        //hashmap保存中序序列的元素数值对应位置
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return findNode(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

    public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
        if (inBegin >= inEnd || postBegin >= postEnd) {
            return null;
        }
        //找到后序遍历最后一个元素在中序序列中的位置
        int rootIndex = map.get(postorder[postEnd - 1]);
        //构造根节点
        TreeNode root = new TreeNode(inorder[rootIndex]);
        //保存中序左子树的个数,用来确定后序序列的个数
        int lenOfLeft = rootIndex - inBegin;
        //构造左子树
        root.left = findNode(inorder, inBegin, rootIndex, postorder, postBegin, postBegin + lenOfLeft);
        //构造右子树
        root.right = findNode(inorder, rootIndex + 1, inEnd, postorder, postBegin + lenOfLeft, postEnd - 1);
        return root;
    }
}

注意

  • 前序和中序序列、后序和中序序列都可以唯一确定一棵二叉树,但前序和后序序列不能唯一确定一棵二叉树。

总结

需要注意一些边界条件的处理,以及利用中序和前序/后序序列构造二叉树时,区间的左闭右开特性需要保持不变。