请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
举个例子,给定一颗叶值序列为 (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)
}