leetcode101題 題解 翻譯 C語言版 Python版__Python

來源:互聯網
上載者:User

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 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. 101.對稱樹 給定一棵二叉樹,檢查它是否是它自身的鏡像(即:軸對稱) 舉個例子,這棵二叉樹是對稱的:

    1   / \  2   2 / \ / \3  4 4  3
但是下面這個就不是:
    1   / \  2   2   \   \   3    3

思路:這題用遞迴很好解決,開始時將左子樹和右子樹分別遞迴下去,如果第一棵樹的左子樹和第二棵樹的右子樹遞迴下去完全相同,同時第一棵樹的右子樹和第二棵樹的左子樹遞迴下去完全相同,那麼這兩棵樹就滿足對稱了。如果根結點的兩棵子樹滿足對稱了,那麼整棵樹就是對稱的了。
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */  bool isSymmetriclr(struct TreeNode* left, struct 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 false;     if (!isSymmetriclr(left->left, right->right)) return false;     if (!isSymmetriclr(left->right, right->left)) return false;     return true; } bool isSymmetric(struct TreeNode* root) {    if (root == NULL) return true;    return isSymmetriclr(root->left, root->right);}


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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.