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

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

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following [1,2,2,null,3,null,3] is not:

        1
       / 
      2   2
          
       3    3
    

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

    想了想 其实就是判断树是不是相等。和之前做的题目类似,我们只要判断左孩子和右孩子这两棵树的左优先遍历和右优先遍历是否相等就可以了

    /**
     * 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 mir(TreeNode *left, TreeNode *right) {
            if (left == NULL && right == NULL) return true;
            if (left == NULL && right != NULL) return false;
            if (left != NULL && right == NULL) return false;
            if (left->val == right->val){
                return mir(left->left,right->right) && mir(left->right,right->left);
            }
            else return false;
        }
        bool isSymmetric(TreeNode* root) {
            if (root == NULL) return true;
            return mir(root->left, root->right);
        }
    };
  • 相关阅读:
    Firefox常用web开发插件
    引用MFC指针的获取(转载)
    J2EE的13种核心技术(转载)
    用Visio画ER图的解决方案(转载)
    [导入]六一
    [导入]独自等待
    [导入]随想
    [导入]小聚
    [导入]网站需求分析
    [导入]如何做好网站开发项目需求分析
  • 原文地址:https://www.cnblogs.com/pk28/p/7218974.html
Copyright © 2011-2022 走看看