[leetcode] 872. 叶子相似的树(周赛)

872. 叶子相似的树

前序遍历,记录叶子节点即可

class Solution {
    private static String ans = "";

    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        ans = "";
        String ans1 = "", ans2 = "";
        fun(root1);
        ans1 = ans;
        ans = "";
        fun(root2);
        ans2 = ans;
        return ans1.equals(ans2);
    }

    public void fun(TreeNode treeNode) {
        if (treeNode.left == null && treeNode.right == null) {
            ans += treeNode.val;
        }
        if (treeNode.left != null) {
            fun(treeNode.left);
        }
        if (treeNode.right != null) {
            fun(treeNode.right);
        }
    }
}

posted @ 2018-07-22 11:34  ACBingo  阅读(374)  评论(0编辑  收藏  举报