叶子相似的树 - LeetCode

请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。

举个例子,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。

如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。

如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。

解法:

深度优先搜索,将叶子节点推入数组

PHP

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root1
     * @param TreeNode $root2
     * @return Boolean
     */
    function leafSimilar($root1, $root2) {
        $leaf1 = [];
        $leaf2 = [];
        $this->dfs($root1, $leaf1);
        $this->dfs($root2, $leaf2);
        return $leaf1 == $leaf2;
    }
    
    function dfs($root, &$leaf) {
        if ($root == null) {
            return;
        }
        if ($root->left == null && $root->right == null) {
            array_push($leaf, $root->val);
            return;
        }
        $this->dfs($root->left, $leaf);
        $this->dfs($root->right, $leaf);
    }
}

GO

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
    var leaf1 []int
    var leaf2 []int
    dfs(root1, &leaf1)
    dfs(root2, &leaf2)
    len := len(leaf1)
    for i := 0; i < len; i++ {
        if leaf1[i] != leaf2[i] {
            return false
        }
    }
    return true
}

func dfs(root *TreeNode, leaf *[]int) {
    if root == nil {
        return
    }
    if root.Left == nil && root.Right == nil {
        *leaf = append(*leaf, root.Val)
        return
    }
    dfs(root.Left, leaf)
    dfs(root.Right, leaf)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值