Problem: 971. 翻转二叉树以匹配先序遍历
题目描述
思路
1.本体大体的思路较好想到直接先序遍历对比元素值,但是在细节处理上还是要多思考:
2.在先序遍历的过程中若当前的左孩子节点不是叶子节点同时和给定的先序遍历序列元素不一致则交换
3.为了避免不必要的递归,可以用一个布尔变量canFlip记录当前已经调整过的序列是否存在不同元素若存在,则说明不存在题目给定的先序遍历序列,则提前退出递归
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数
空间复杂度:
O ( h ) O(h) O(h);其中 h h h为二叉树的高度
Code
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
this.voyage = voyage;
traverse(root);
if (canFlip) {
return res;
}
return Arrays.asList(-1);
}
int i = 0;
int[] voyage;
boolean canFlip = true;
private void traverse(TreeNode root) {
if (root == null || !canFlip) {
return;
}
// If the val of the node does not match,
// there must be no solution
if (root.val != voyage[i++]) {
canFlip = false;
return;
}
// The preorder traversal result is incorrect.
// Try to flip the left and right subtrees
if (root.left != null && root.left.val != voyage[i]) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// Record the flip node
res.add(root.val);
}
traverse(root.left);
traverse(root.right);
}
}