LeetCodeOJ. Symmetric Tree

試題請參見: https://oj.leetcode.com/problems/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:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means?

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

解題思路

一般的考慮是遞歸, 遞歸判斷左孩子的左子樹與右孩子的右子樹以及左孩子的右子樹與右孩子的左子樹是否相等.

遇到的問題

一共192個測試測試點, 簡直喪心病狂.
除了判斷結構是否對稱以外, 還需要判斷數值是否相同.
一開始沒有判斷, 於是就WA了.

源代碼

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if ( root == NULL ) {
            return true;
        } else {
            return isSymmetric(root->left, root->right);
        }
    }
private:
    bool isSymmetric(TreeNode *left, TreeNode *right) {
        if ( left == NULL && right == NULL ) {
            return true;
        } else if ( left != NULL && right != NULL ) {
            if ( left->val != right->val ) {
                return false;
            } 

            if ( isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left) ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
};


發佈了50 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章