LeetCode题库解答与分析——#101. 对称二叉树SymmetricTree

给定一个二叉树,检查它是否是它自己的镜像(即,围绕它的中心对称)。

例如,这个二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

但是下面这个 [1,2,2,null,3,null,3] 则不是:

    1
   / \
  2   2
   \   \
   3    3

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

个人思路:

把根节点的左右节点看做两棵树的根节点,与相同的树思路类似,利用深度优先搜索同时遍历两棵树的所有节点,不同的是,要以对称的方向将两棵树的节点进栈、出栈,如左树的左子节点和右树的右子节点同时进栈,同样在每次出栈时比较两数值是否相等,进栈后比较栈长度是否一致,如有不同则立刻返回false,坚持到最后则返回true。

扫描二维码关注公众号,回复: 5889333 查看本文章

代码(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) {
        if(root==null){return true;}

        Stack<TreeNode> pstack=new Stack<TreeNode>();  
        Stack<TreeNode> qstack=new Stack<TreeNode>(); 
        TreeNode p=null,q=null;
        
        if(root.left!=null){p=root.left;}
        if(root.right!=null){q=root.right;}
            
        if(p!=null) pstack.push(p);  
        if(q!=null) qstack.push(q); 
        if(pstack.size()!=qstack.size()){return false;}
        while (!pstack.isEmpty()&&!qstack.isEmpty()) {  
            p=pstack.pop();  
            q=qstack.pop();
            
            if(p.val!=q.val){return false;}
  
            if(p.right!=null){pstack.push(p.right);}
            if(q.left!=null){qstack.push(q.left);}
            if(pstack.size()!=qstack.size()){return false;}
            
            if(p.left!=null){pstack.push(p.left);}
            if(q.right!=null){qstack.push(q.right);}
            if(pstack.size()!=qstack.size()){return false;}
        }
        return pstack.size()==qstack.size();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38385524/article/details/79864895
今日推荐