• 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;
            }
        }
    };
    以大多数人努力程度之低,根本轮不到去拼天赋~
  • 相关阅读:
    spring_150807_hibernate_transaction_annotation
    快速排序算法
    组合数递推算法
    HDU 4832 Chess(DP+组合数)
    HDU 2602 Bone Collector (01背包)
    HDU 1597 find the nth digit (二分查找)
    HDU1163 Eddy's digital Roots(九余数定理)
    HDU1031 Design T-Shirt (二级排序)
    HDU1719 Friend (数学推导)
    HDU1720 A+B Coming (16进制加法)
  • 原文地址:https://www.cnblogs.com/gcter/p/15338378.html
Copyright © 2020-2023  润新知