Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Symmetric Tree

Easy · Trees · Asked at Amazon, Microsoft, LinkedIn, Bloomberg

Print YES if the tree is a mirror image of itself around its centre, otherwise NO.

Input

First line: k. Second line: k values — the tree in level order, -1 means no node.

Output

YES or NO.

Constraints

Compare the left subtree with the right subtree mirrored: a.left vs b.right and a.right vs b.left.

Example 1

Input

7
1 2 2 3 4 4 3

Output

YES

Example 2

Input

7
1 2 2 -1 3 -1 3

Output

NO

Hints

  1. A tree is symmetric when its left subtree is a mirror of its right subtree.
  2. Two trees a and b are mirrors if their roots are equal, a.left mirrors b.right and a.right mirrors b.left.

Approach

mirror(a, b) works like the identical-tree check but crosses the children: compare a.left with b.right and a.right with b.left. The answer is mirror(root.left, root.right).

Complexity: O(n) time · O(h) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

// Build a tree from level order where -1 means "no node".
Node *readTree() {
    int k;
    cin >> k;
    vector<long long> v(k);
    for (auto &x : v) cin >> x;
    if (k == 0 || v[0] == -1) return nullptr;
    Node *root = new Node(v[0]);
    queue<Node *> q;
    q.push(root);
    int i = 1;
    while (!q.empty() && i < k) {
        Node *cur = q.front();
        q.pop();
        if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
        i++;
        if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
        i++;
    }
    return root;
}

bool mirror(Node *a, Node *b) {
    if (!a || !b) return a == b;
    return a->val == b->val && mirror(a->left, b->right) && mirror(a->right, b->left);
}

int main() {
    Node *root = readTree();
    cout << (mirror(root->left, root->right) ? "YES" : "NO") << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

sys.setrecursionlimit(100000)

class Node:
    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build_tree(v):
    """Build a tree from level order where -1 means "no node"."""
    if not v or v[0] == -1:
        return None
    root = Node(v[0])
    q, i = deque([root]), 1
    while q and i < len(v):
        cur = q.popleft()
        if i < len(v) and v[i] != -1:
            cur.left = Node(v[i])
            q.append(cur.left)
        i += 1
        if i < len(v) and v[i] != -1:
            cur.right = Node(v[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]


def mirror(a, b):
    if not a or not b:
        return a is b
    return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)


print("YES" if mirror(root.left, root.right) else "NO")

Java solution

import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    // Build a tree from level order where -1 means "no node".
    static Node readTree(Scanner sc) {
        int k = sc.nextInt();
        long[] v = new long[k];
        for (int i = 0; i < k; i++) v[i] = sc.nextLong();
        if (k == 0 || v[0] == -1) return null;
        Node root = new Node(v[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < k) {
            Node cur = q.poll();
            if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
            i++;
            if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
            i++;
        }
        return root;
    }

    static boolean mirror(Node a, Node b) {
        if (a == null || b == null) return a == b;
        return a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left);
    }

    public static void main(String[] args) {
        Node root = readTree(new Scanner(System.in));
        System.out.println(mirror(root.left, root.right) ? "YES" : "NO");
    }
}

Solve Symmetric Tree online · All practice problems