LeetCode 872. Similar tree leaf (Leaf-Similar Trees)

872. Similar leaves of the tree
872. Leaf-Similar Trees

Title Description
Consider all the leaves on a binary tree, the value of the leaves are arranged in order from the left lobe forming a sequence of values.

LeetCode 872. Similar Trees Leaf- simple

For example, as shown above, a given sequence of values ​​of a leaf (6, 7, 4, 9, 8) of the tree.

If there are two sequences of binary tree leaf values are the same, then we think they are similar to the leaves  of.

If two given nodes of the head and root2 root1 tree leaves are similar, it returns true; otherwise returns false.

prompt:

  • Given two trees may be 1 to 100 nodes.

Java implementation
TreeNode Class

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        if (root1 == null || root2 == null) {
            return root1 == null && root2 == null ? true : false;
        }
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        preorder(root1, sb1);
        preorder(root2, sb2);
        return sb1.toString().equals(sb2.toString());
    }

    public void preorder(TreeNode root, StringBuffer sb) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            sb.append(root.val);
        }
        preorder(root.left, sb);
        preorder(root.right, sb);
    }
}

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/10994616.html