101 对称二叉树
C++代码(递归):
递归的判断两个结点是否相等,两个结点都为空则相等,两个结点一个为空则不相等,两个结点都不为空但如果他们的val相等且左右子树也相等,则这两个结点相等,左右子树的判断又可以通过比较两两对称的结点。
/** * 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) { return isMirro(root,root); } bool isMirro(TreeNode* t1, TreeNode* t2){ if(t1 == NULL && t2 == NULL) return true; if(t1 == NULL || t2 == NULL) return false; return (t1->val == t2->val) && isMirro(t1->left, t2->right) && isMirro(t1->right, t2->left); } };
java代码(迭代法):
用一个链表,把树的每一层按对称方式 的去存储树节点,然后依次取出来比较。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { Queue<TreeNode> que = new LinkedList<TreeNode>(); que.add(root); que.add(root); while(!que.isEmpty()){ TreeNode t1 = que.poll(); TreeNode t2 = que.poll(); if(t1 == null && t2 == null) continue; if(t1 == null || t2 == null) return false; if(t1.val == t2.val){ que.add(t1.left); que.add(t2.right); que.add(t1.right); que.add(t2.left); }else{ return false; } } return true; } }