Try   HackMD

951. Flip Equivalent Binary Trees


My Solution

The Key Idea for Solving This Coding Question

DFS (recursion) preorder traversal.
If both subtrees are not empty, visit the subtree whose root value is smaller.

C++ Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool flipEquiv(TreeNode *root1, TreeNode *root2) { vector<int> traversal1, traversal2; dfs(root1, traversal1); dfs(root2, traversal2); return traversal1 == traversal2; } private: void dfs(TreeNode *root, vector<int> &traversal) { if (root == nullptr) { traversal.push_back(-1); return; } traversal.push_back(root->val); if (root->left == nullptr) { dfs(root->right, traversal); traversal.push_back(-1); return; } if (root->right == nullptr) { dfs(root->left, traversal); traversal.push_back(-1); return; } if (root->left->val < root->right->val) { dfs(root->left, traversal); dfs(root->right, traversal); return; } dfs(root->right, traversal); dfs(root->left, traversal); } };

Time Complexity

O(n)
n
is the number of nodes in the binary tree.

Space Complexity

O(H)
H
is the height of the binary tree.

Miscellaneous