题目所属分类
判断对称二叉树 的递归和迭代写法
原题链接
给你一个二叉树的根节点 root , 检查它是否轴对称。
代码案例:
输入:root = [1,2,2,3,4,4,3]
输出:true
题解
递归解法
递归判断两个子树是否互为镜像。
两个子树互为镜像当且仅当:
两个子树的根节点值相等;
第一棵子树的左子树和第二棵子树的右子树互为镜像,且第一棵子树的右子树和第二棵子树的左子树互为镜像;
时间复杂度分析:从上到下每个节点仅被遍历一遍,所以时间复杂度是 O(n) 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return dfs(root.left,root.right);
}
public boolean dfs(TreeNode p ,TreeNode q){
if(p == null && q== null) return true;
if(p == null || q == null) return false;
return p.val == q.val && dfs(p.left,q.right) && dfs(p.right,q.left);
}
}
迭代解法
用栈模拟递归,对根节点的左子树,我们用中序遍历;对根节点的右子树,我们用反中序遍历。
则两个子树互为镜像,当且仅当同时遍历两课子树时,对应节点的值相等。
时间复杂度分析:树中每个节点仅被遍历一遍,所以时间复杂度是 O(n) 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return dfs(root.left, root.right);
}
boolean dfs(TreeNode p, TreeNode q) {
Deque<TreeNode> stk = new LinkedList<>();
stk.push(p);
stk.push(q);
TreeNode tp, tq;
while (!stk.isEmpty()) {
tq = stk.pop();
tp = stk.pop();
if (tp == null && tq == null) {
continue;
}
if (tp == null || tq == null || tp.val != tq.val) {
return false;
}
stk.push(tp.left);
stk.push(tq.right);
stk.push(tp.right);
stk.push(tq.left);
}
return true;
}
}