码迷,mamicode.com
首页 > 其他好文 > 详细

101. Symmetric Tree

时间:2016-05-17 11:29:53      阅读:140      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!