Formatted question description: https://leetcode.ca/all/971.html

971. Flip Binary Tree To Match Preorder Traversal (Medium)

Given a binary tree with N nodes, each node has a different value from {1, ..., N}.

A node in this binary tree can be flipped by swapping the left child and the right child of that node.

Consider the sequence of N values reported by a preorder traversal starting from the root.  Call such a sequence of N values the voyage of the tree.

(Recall that a preorder traversal of a node means we report the current node's value, then preorder-traverse the left child, then preorder-traverse the right child.)

Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyage we are given.

If we can do so, then return a list of the values of all nodes flipped.  You may return the answer in any order.

If we cannot do so, then return the list [-1].

 

Example 1:

Input: root = [1,2], voyage = [2,1]
Output: [-1]

Example 2:

Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]

Example 3:

Input: root = [1,2,3], voyage = [1,2,3]
Output: []

 

Note:

  1. 1 <= N <= 100

Related Topics:
Tree, Depth-first Search

Solution 1.

// OJ: https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/

// Time: O(NlogN)
// Space: O(logN)
class Solution {
private:
    vector<int> ans;
    int find(vector<int>& v, int begin, int end, int target) {
        int i = begin;
        while (i < end && v[i] != target) ++i;
        return i;
    }
    bool preorder(TreeNode *root, vector<int>& voyage, int begin, int end) {
        if (!root) return end == begin;
        if (end == begin || voyage[begin] != root->val) return false;
        if (!root->left && !root->right) return begin + 1 == end;
        int leftIndex = end, rightIndex = end;
        if (root->right) {
            rightIndex = find(voyage, begin + 1, end, root->right->val);
            if (rightIndex == end) return false;
        }
        if (root->left) {
            leftIndex = find(voyage, begin + 1, end, root->left->val);
            if (leftIndex == end) return false;
        }
        if (preorder(root->left, voyage, begin + 1, rightIndex)
                && preorder(root->right, voyage, rightIndex, end)) return true;
        if (preorder(root->left, voyage, leftIndex, end)
                && preorder(root->right, voyage, begin + 1, leftIndex)) {
            ans.push_back(root->val);
            return true;
        }
        return false;
    }
public:
    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
        if (preorder(root, voyage, 0, voyage.size())) return ans;
        return { -1 };
    }
};

Solution 2.

Instead of searching the values, just test if the value of the left node (if any) equals the next element:

  • if it does, dfs left first then right
  • otherwise, dfs right first then left
// OJ: https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/

// Time: O(N)
// Space: O(logN)
class Solution {
private:
    vector<int> ans;
    bool dfs(TreeNode* root, vector<int>& voyage, int &i) {
        if (!root) return true;
        if (root->val != voyage[i]) return false;
        ++i;
        if (root->left && root->left->val != voyage[i]) {
            ans.push_back(root->val);
            return dfs(root->right, voyage, i) && dfs(root->left, voyage, i);
        }
        return dfs(root->left, voyage, i) && dfs(root->right, voyage, i);
    }
public:
    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
        int i = 0;
        if (dfs(root, voyage, i)) return ans;
        return { - 1 };
    }
};

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
        if (root == null)
            return new ArrayList<Integer>();
        Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
        int length = voyage.length;
        for (int i = 0; i < length; i++)
            indexMap.put(voyage[i], i);
        List<Integer> flipList = new ArrayList<Integer>();
        int voyageIndex = 0;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            if (voyageIndex >= length)
                return new ArrayList<Integer>(Arrays.asList(-1));
            TreeNode node = stack.pop();
            if (node.val != voyage[voyageIndex])
                return new ArrayList<Integer>(Arrays.asList(-1));
            voyageIndex++;
            TreeNode left = node.left, right = node.right;
            if (left != null && right != null && right.val == voyage[voyageIndex]) {
                flipList.add(node.val);
                stack.push(left);
                stack.push(right);
            } else {
                if (right != null)
                    stack.push(right);
                if (left != null)
                    stack.push(left);
            }
        }
        if (voyageIndex != length)
            return new ArrayList<Integer>(Arrays.asList(-1));
        return flipList;
    }
}

All Problems

All Solutions