1. 程式人生 > >LeetCode(51) Symmetric Tree

LeetCode(51) Symmetric Tree

題目描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

symmetric tree

But the following is not:

not symmetric tree

判斷一棵二叉樹是否對稱。

解題思路

根據題目要求,可以認為是樹的層序遍歷的一種應用。可以遞迴的判斷樹的左右子樹是否相等。

  • 根節點直接遞迴判斷左右子樹即可;
  • 對於根節點一下的結點,需要判斷
    • 左結點的左子樹和右結點的右子樹;
    • 左結點的右子樹和右結點的左子樹
/**
 * 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:
    bool isSame(TreeNode* left, TreeNode* right)
    {
        if
(!left && !right) return true; if(left && !right || !left && right) return false; if(left->val != right->val) return false; return isSame(left->left, right->right) && isSame(left->right, right->left); } bool isSymmetric(TreeNode* root) { if
(!root) return true; return isSame(root->left, root->right); } };