代码随想录算法训练营 day 18: 112. 路径总和 | 106.从中序与后序遍历序列构造二叉树

84 阅读1分钟

112. Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

leaf is a node with no children.

 

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

递归在叶子节点判断路径和是否等于target即可。

/**
 * 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 {
    boolean moutput = false;
    void rcHelper(TreeNode root, int sum, int targetSum) {
        if(root == null) {
            return;
        }

        if(root.left == null && root.right == null) {
            if(sum + root.val == targetSum) {
                moutput = true;
            }
            return;
        }

        rcHelper(root.left, sum + root.val, targetSum);
        rcHelper(root.right, sum + root.val, targetSum);
    }
    public boolean hasPathSum(TreeNode root, int targetSum) {
        rcHelper(root, 0, targetSum);

        return moutput;
    }
}

106. Construct Binary Tree from Inorder and Postorder Traversal

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

 

Example 1:

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: inorder = [-1], postorder = [-1]
Output: [-1]

 

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.

这题一开始没思路。后序遍历是先左子树,再右子树,再根节点,所以最后一个元素一定是根节点。 递归步骤为:

  1. 创建当前节点。取后序遍历数组的最后一个元素,在中序遍历数组里找这个元素,返回index
  2. 以返回的index为界,将中序数组分为两个,返回的元素不在任何一个内。两个数组需保存
  3. 以分开的两个中序数组的长度为准,将后序数组按长度分割,得到两个后序数组,保存下来。
  4. 递归调用左子节点输入中序数组1,后序数组1, 右子节点输入中序数组2,后序数组2
  5. 返回当前节点。

注意边界条件。

/**
 * 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 {
    TreeNode rcHelper( int[] inorder, int[] postorder) {
        if(postorder.length < 1 || inorder.length != postorder.length) {
            return null;
        } 

        int delimiterIdx = postorder.length - 1;
        int delimiterVal = postorder[delimiterIdx];
        //System.out.println(delimiterVal);

        TreeNode root = new TreeNode(delimiterVal);

        int delimiterIdxInorder = 0;

        for(;delimiterIdxInorder<inorder.length; delimiterIdxInorder++) {
            if(inorder[delimiterIdxInorder] == delimiterVal) {
                break;
            }
        }
            //System.out.println(delimiterIdxInorder);
        int[] larray = new int[0];
        int[] rarray = new int[0];
        //System.out.println("1===========");

        if(delimiterIdxInorder > 0) {
            //inorder has left part
            larray = Arrays.copyOfRange(inorder, 0, delimiterIdxInorder);
            //System.out.println(larray.length);
        }

        if(delimiterIdxInorder < inorder.length - 1) {
            //inorder has right part

            rarray = Arrays.copyOfRange(inorder, delimiterIdxInorder+1, inorder.length);
            //System.out.println(rarray.length);

        }
            //System.out.println("2===========");

        int[] lparray = new int[0];
        int[] rparray = new int[0];
         //System.out.println("llen = " + Integer.toString(larray.length) + ", rlen = " + Integer.toString(rarray.length));

        if(larray.length > 0) {
            lparray = Arrays.copyOfRange(postorder, 0, larray.length);
            //System.out.println("lparray len = " + Integer.toString(lparray.length));

        }

        if(rarray.length > 0) {
            rparray = Arrays.copyOfRange(postorder, larray.length, postorder.length - 1);
            //System.out.println("rparray len = " + Integer.toString(rparray.length));

        }
            //System.out.println("3===========");


        root.left = rcHelper(larray, lparray);
        root.right = rcHelper(rarray, rparray);

        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return rcHelper(inorder, postorder);
    }
}