LeetCode.872: Leaf-Similar Trees

版权声明:转载请注明出处 https://blog.csdn.net/lcpskk/article/details/82695264

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

answer:

public class Solution {
    public void TraverseNode(StringBuilder leafStr,TreeNode node)
        {
            if (node == null)
            {
                return;
            }
            if (node.left == null && node.right == null)
            {
                if (leafStr == null)
                {
                    leafStr = new StringBuilder();
                }
                leafStr.Append(node.val+"-");
            }
            if (node.left != null)
            {
                TraverseNode(leafStr, node.left);
            }
            if (node.right != null)
            {
                TraverseNode(leafStr, node.right);
            }
        }
        public bool LeafSimilar(TreeNode root1, TreeNode root2)
        {
            StringBuilder strLeaf1 = new StringBuilder();
            StringBuilder strLeaf2 = new StringBuilder();

            TraverseNode(strLeaf1, root1);
            TraverseNode(strLeaf2, root2);

            return strLeaf1.Equals(strLeaf2);
        }
}

猜你喜欢

转载自blog.csdn.net/lcpskk/article/details/82695264
今日推荐