[leetcode]971. Flip Binary Tree To Match Preorder Traversal

162 篇文章 0 订阅
53 篇文章 0 订阅

[leetcode]971. Flip Binary Tree To Match Preorder Traversal


Analysis

昨天和今天天气都很好鸭~嘻嘻—— [每天刷题并不难0.0]

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].
在这里插入图片描述

Explanation:

先序遍历给定的树,同时遍历voyage,如果节点值等于voyage里的值,但是左儿子的值不等于voyage里的值,则调换左右儿子节点,继续遍历

Implement

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
        return dfs(root, voyage)?res:vector<int>{-1};
    }
    bool dfs(TreeNode* node, vector<int>& voyage){
        if(!node)
            return true;
        if(node->val != voyage[i++])
            return false;
        if(node->left && node->left->val != voyage[i]){
            res.push_back(node->val);
            return dfs(node->right, voyage) && dfs(node->left, voyage);
        }
        return dfs(node->left, voyage) && dfs(node->right, voyage);
    }
private:
    vector<int> res;
    int i;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值