zoukankan      html  css  js  c++  java
  • leetcode 101. 对称二叉树

    思路 递归

    用一个函数辅助判断左右子树是否完全对称,对根节点进行输入递归判断结果。

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isSymmetric(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if not root:
                return True
            return self.judge_is_sys(root,root)
        def judge_is_sys(self,proot1,proot2):
            if not proot1 and not proot2:
                return True
            if not proot1 or not proot2:
                return False
            if proot1.val == proot2.val:
                return self.judge_is_sys(proot1.left,proot2.right) and self.judge_is_sys(proot1.right,proot2.left)
            else:
                return False

    C++代码:

    /**
     * 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 judge_is_sys(root,root);
        }
        bool judge_is_sys(TreeNode* root1,TreeNode*  root2)
        {
            if (root1 == NULL && root2 == NULL)
            {
                return true;
            }
            if(root1 == NULL || root2 == NULL)
            {
                return false;
            }
            if (root1->val  == root2->val)
            {
                return judge_is_sys(root1->right,root2->left)&&judge_is_sys(root1->left,root2->right);
            }
            else
            {
                return false;
            }
        }
    };
    以大多数人努力程度之低,根本轮不到去拼天赋~
  • 相关阅读:
    学校的破网,你别再掉了
    PhotoShop SDK的获取
    我的C++博客开张了
    一个新的嵌入式门户
    试用Bloglines.com
    PhotoShop的插件体系
    VB6 to VB.NET Migration Guide Community Preview #4
    看看Microsoft都买了些什么
    Borland CTO辞职
    PhotoShop插件的开发
  • 原文地址:https://www.cnblogs.com/gcter/p/15338378.html
Copyright © 2011-2022 走看看