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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
思路:用DFS,首先左树与右树的结点开始值要相等,然后再将左树的左子树与右树的右子树比较,接着是左树的右子树与右树的左子树比较
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private boolean checkSymmetric(TreeNode left, TreeNode right) { if (left == null && right == null) return true; if (left == null || right == null) return false; if (left.val != right.val) return false; return checkSymmetric(left.left, right.right) && checkSymmetric(left.right, right.left); } public boolean isSymmetric(TreeNode root) { if (root == null) return true; return checkSymmetric(root.left, root.right); } }
第二种方法:用非递归方法,实际上就是模拟递归的入栈,出栈操作
/** * Definition for binary tree * 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; queue<TreeNode*> left, right; left.push(root->left); right.push(root->right); while (!left.empty() && !right.empty()) { TreeNode *curLeft = left.front(); left.pop(); TreeNode *curRight = right.front(); right.pop(); if (curLeft == NULL && curRight == NULL) continue; if (curLeft == NULL || curRight == NULL) return false; if (curLeft->val != curRight->val) return false; left.push(curLeft->left), right.push(curRight->right); left.push(curLeft->right), right.push(curRight->left); } return true; } };