zoukankan      html  css  js  c++  java
  • Leetcode 101. Symmetric Tree

    Given two binary trees, write a function to check if they are the same or not.

    Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

    Example 1:

    Input: 1 1
    / /
    2 3 2 3

    [1,2,3], [1,2,3]

    Output: true
    Example 2:

    Input: 1 1
    /
    2 2

    [1,2], [1,null,2]

    Output: false
    Example 3:

    Input: 1 1
    / /
    2 1 1 2

    [1,2,1], [1,1,2]

    Output: false

    这道题目,我们借用一个isMirror函数,判断左右是否相等。
    在isSymmetric中,我们判定root是空,则返回true,否则返回isMirror判定左右子树
    isMirror中,我们判定两个都为空,那么遍历到了最底部,返回true,如果两个都不为空,并且值相等,那就递归一下,继续比较。
    如果都不满足,则false

    /**
     * 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 isSymmetric(TreeNode* root) {
            if(root == NULL) return true;
            return isMirror(root->left, root->right);
        }
        bool isMirror(TreeNode* p, TreeNode* q) {
            if(p == NULL && q == NULL) return true;
            if(p != NULL && q != NULL && p->val == q->val)
                return isMirror(p->left, q->right) && isMirror(p->right, q->left); 
            return false;
        }
    };
  • 相关阅读:
    IPFS学习-DNS链接
    IPFS学习-内容标识符(CIDs)
    IPFS学习-分布式哈希表DHT
    CURL命令学习一
    Hyperledger Fabric 动态增加组织到网络中
    Fabric-Ca使用
    Hyperledger Fabric手动生成CA证书搭建Fabric网络
    Hyperledger Fabric私有数据
    Idea 第一个Struts2程序
    jQuery总结
  • 原文地址:https://www.cnblogs.com/littlepage/p/12271775.html
Copyright © 2011-2022 走看看