Symmetric Binary Tree

题目:

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

分析:

这题目想法并不难,但是一定要注意到,这是一个需要两个参数的递归,是不能用给的接口本身进行递归的。

此外,这道题目的非递归方法我没有做。

解法:

class Solution {
public:
    /**
     * @param root, the root of binary tree.
     * @return true if it is a mirror of itself, or false.
     */
    bool dfs(TreeNode* A, TreeNode* B) {
        if (A == NULL && B == NULL) {
            return true;
        }
        if (A == NULL || B == NULL) {
            return false;
        }
        if (A->val != B->val) {
            return false;
        }
        return (dfs(A->left, B->right) ) && (dfs(A->right, B->left) );
    } 
    bool isSymmetric(TreeNode* root) {
        // Write your code here
        if (root == NULL) {
            return true;
        }
        return dfs(root->left, root->right);
    }
};

results matching ""

    No results matching ""