Flip Binary Tree To Match Preorder Traversal
Example
Input:
root = [1,2], voyage = [2,1]
Output:
[-1]Input:
root = [1,2,3], voyage = [1,3,2]
Output:
[1]Note
Code
Last updated
Input:
root = [1,2], voyage = [2,1]
Output:
[-1]Input:
root = [1,2,3], voyage = [1,3,2]
Output:
[1]Last updated
Input:
root = [1,2,3], voyage = [1,2,3]
Output:
[]public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
List<Integer> res = new ArrayList<>();
int i = 0;
Stack<TreeNode> s = new Stack<>();
s.push(root);
while (!s.isEmpty()) {
TreeNode curr = s.pop();
if (curr == null) { continue; }
if (curr.val != voyage[i++]) { return Arrays.asList(-1); }
if (curr.right != null && curr.right.val == voyage[i]) {
if (curr.left != null) { // 针对1-null-2,【1,2】的情况
res.add(curr.val);
}
s.push(curr.left);
s.push(curr.right);
} else {
s.push(curr.right);
s.push(curr.left);
}
}
return res;
}List<Integer> res = new ArrayList<>();
int i = 0;
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
if (dfs(root, voyage)) {
return res;
}
return Arrays.asList(-1);
}
private boolean dfs(TreeNode root, int[] v) {
if (root == null) {
return true;
}
if (root.val != v[i++]) {
return false;
}
if (root.left != null && root.left.val != v[i]) {
res.add(root.val);
return dfs(root.right, v) && dfs(root.left, v);
} else {
return dfs(root.left, v) && dfs(root.right, v);
}
}