zoukankan      html  css  js  c++  java
  • Leetcode题目: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.

    题目解答:需要判断一棵树是不是对称的,其实就是比较左子树的左节点和右子树的右节点是否对称以及左子树的右节点和右子树的左节点是否对称。依旧使用递归来解决问题。

    根据此,可以写出下面的代码:

    /**
     * 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) || (root -> left == NULL) && (root -> right == NULL) )
                return true;
            else if((root -> left != NULL) && ( root -> right != NULL) && (root -> left -> val == root -> right -> val) )
            {
                return judgeSymNode(root -> left,root -> right);
            }
            else
                return false;
        }
       
        bool judgeSymNode(TreeNode * leftNode,TreeNode *rightNode)
        {
            if((leftNode == NULL) && (rightNode == NULL))
                return true;
            else if((leftNode == NULL) || (rightNode == NULL))
                return false;
            else if(leftNode -> val != rightNode -> val)
                return false;
            else
            {
                return judgeSymNode(leftNode -> left,rightNode -> right) && judgeSymNode(leftNode -> right,rightNode -> left);
            }
        }
       
    };

  • 相关阅读:
    tmux 简明操作指南
    几种查看linux版本信息的方法
    安装Ruby&Rails遇到的问题
    安装DevKit
    gcc 编译选项
    EF数据操作详解
    值类型和引用类型的区别
    Class<T> where T:new() 含义
    50道高级sql练习题;大大提高自己的sql能力(附具体的sql)
    Entity framework 意外删除了表,如何在不影响其它表的情况下恢复回来
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5426186.html
Copyright © 2011-2022 走看看