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