971. Flip Binary Tree To Match Preorder Traversal
T: O(n)
S: O(n)
/**
* 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 {
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
List<Integer> result = new ArrayList<>();
int[] i = new int[1];
boolean res = dfs(root, voyage, i, result);
if (!res) {
return List.of(-1);
}
return result;
}
private boolean dfs(TreeNode root, int[] voyage, int[] i, List<Integer> result) {
if (root == null) {
return true;
}
if (root.val != voyage[i[0]++]) { // root val is wrong, means can't flip to make it
return false;
}
if (root.left != null && root.left.val != voyage[i[0]]) { // left not the same, do swap
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
result.add(root.val);
}
return dfs(root.left, voyage, i, result) && dfs(root.right, voyage, i, result);
}
}
/***
T: O(n)
S: O(n)
*/
Last updated