Symmetric tree
Given a binary tree, check whether it's a mirror of itself (ie, symmetric around its center).
For example, this binary the 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. Symmetric tree Given a binary tree, check whether it is its own mirror image (that is, axisymmetric) For example, this binary tree is symmetrical:
1
/\
2 2
/\/\
3 4 4 3
But this is not the following:
1
/\
2 2
\ \
3 3
Train of thought: This problem solves with recursion very well, at the beginning will Saozi the right subtree of tree to go down separately, if the right subtree of the second tree of the first tree is Saozi exactly the same, and the right subtree of the first tree and the Zuozi of the second tree are recursively identical, then the two trees will satisfy symmetry. If the two Shang trees of the root knot satisfy symmetry, then the whole tree is symmetrical.
/**
* 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 = None
class Solution (object):
def issymmetric (self, Root): ""
: Type root: TreeNode
: Rtype:bool
""
if not Root:return True
to return self.issymmetriclr (Root.left, Root.right
def issymmetriclr (self, left, right):
if not (left or right): "Return True
if" (left and Right==n One) or (Left==none and right): return
False
if Left.val!= right.val:return false
if not self.issymmetric LR (Left.left, right.right): return false
if not SELF.ISSYMMETRICLR (Left.right, Right.left): Return False
Return True