971. 翻转二叉树以匹配先序遍历

56 阅读1分钟

题目:
给你一棵二叉树的根节点 root ,树中有 n 个节点,每个节点都有一个不同于其他节点且处于 1 到 n 之间的值。

另给你一个由 n 个值组成的行程序列 voyage ,表示 预期 的二叉树 先序遍历 结果。

通过交换节点的左右子树,可以 翻转 该二叉树中的任意节点。例,翻转节点 1 的效果如下:

算法:
方法一:dfs
自己做出来了,happy,不过不知道为什么这样翻转是次数最少。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func flipMatchVoyage(root *TreeNode, voyage []int) []int {
    // visited := make(map[int]bool, 0)
    ans := make([]int, 0)
    index := 0 
    var dfs func(node *TreeNode)
    dfs = func(node *TreeNode) {
        // 也可以用另外一个全局变量true false判断能否翻转,而不用(len(ans) != 0 && ans[0] == -1)
        if node == nil || (len(ans) != 0 && ans[0] == -1){
            return 
        }
        if node.Val != voyage[index] {
            
            ans = []int{-1}
            return
        }
        if node.Left != nil && index + 1 < len(voyage) && node.Left.Val != voyage[index + 1]{
            // 左子节点不相等交换。
            // 如果node的左子节点相等,右子节点不等,则会触发上上个if条件,无法翻转实现匹配
            node.Left, node.Right = node.Right, node.Left
            ans = append(ans, node.Val)
        }
        index ++
        dfs(node.Left)
        dfs(node.Right)
    }
    dfs(root)
    return ans
}