树的总结--树的性质II leetcode

发布时间:2019-06-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了树的总结--树的性质II leetcode脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Same Tree

Given two binary trees, write a function to check if they are equal or
not.

Two binary trees are considered equal if they are structurally
identical and the nodes have the same value.

递归解法

复杂度

时间O(n) 空间栈 O(logn)

代码

public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {//p或者q只有一方是null
            return false;
        }
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

Subtree

You have two every large binary trees: T1, with millions of nodes, and
T2, with hundreds of nodes. Create an algorithm to decide if T2 is a
subtree of T1.

递归解法

思路:

递归退出条件是T1或者T2是空, 如果T2是空那么T2是T1的子树, 返回true 如果T1是空 返回false.
递归的条件是T2和T1是same tree 或者T2是T1的子树的subtree

代码

public boolean isSubtree(TreeNode T1, TreeNode T2) {
        if (T2 == null) {
            return true;
        }
        if (T1 == null) {
            return false;
        }
        return isSame(T1, T2) || isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
    }

Symmetric Tree

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

递归解法

思路

与sametree思路相同, 不过递归条件是左子树与右子树想对比

复杂度

时间O(n) 空间栈O(logn)

代码

public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return helper(root.left, root.right);
    }
    public boolean helper(TreeNode node1, TreeNode node2) {
        if (node1 == null && node2 == null) {
            return true;
        }
        if (node1 == null || node2 == null) {
            return false;
        }
        if (node1.val != node2.val) {
            return false;
        }
        return helper(node1.left, node2.right) && helper(node2.left, node1.right);

脚本宝典总结

以上是脚本宝典为你收集整理的树的总结--树的性质II leetcode全部内容,希望文章能够帮你解决树的总结--树的性质II leetcode所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: