首页 > 其他 > 详细

101. Symmetric Tree

时间:2016-05-17 11:29:40      阅读:183      评论:0      收藏:0      [点我收藏+]
    /*
     * 101. Symmetric Tree 
     * 2016-5-16 By Mingyang 
     * 刚开始的时候只有一个root做不行,后面改过来,下面是标准的英文回答时间复杂度和空间复杂度的表述
     * Because we traverse the entire input tree once, the total run time is O(n)O(n), 
     * where nn is the total number of nodes in the tree.
     * The number of recursive calls is bound by the height of the tree. 
     * In the worst case, the tree is linear and the height is in O(n)O(n). 
     * Therefore, space complexity due to recursive calls on the stack is O(n)O(n) in the worst case.
     * 当然我们可以用擅长的queue来做
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return isSymmetricTree(root.left, root.right);
    }
    public boolean isSymmetricTree(TreeNode p, TreeNode q) {
        if (p == null && q == null)
            return true;
        if (p == null || q == null)
            return false;
        return (p.val == q.val) && isSymmetricTree(p.left, q.right)&& isSymmetricTree(p.right, q.left);
    }

 

101. Symmetric Tree

原文:http://www.cnblogs.com/zmyvszk/p/5500418.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!