Description:
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.
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.
Note:
- Both of the given trees will have between
1
and100
nodes.
分析:此题需要分别获取两个二叉树所有叶子节点的值,可存入list进行比较。题解用前序遍历来获取所有叶子节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
getAllChild(root1,1);
getAllChild(root2,2);
if(a.size()!=b.size())
return false;
for(int i = 0; i < a.size(); i++){
if(a.get(i)!=b.get(i))
return false;
}
return true;
}
//前序遍历获取所有叶子节点
public void getAllChild(TreeNode root,int number){
if(root != null){
if(root.left == null && root.right == null){
if(number==1)
a.add(root.val);
else
b.add(root.val);
}
getAllChild(root.left,number);
getAllChild(root.right,number);
}
}
}
这个方法可以AC,但运行时间只超过了23%的java提交。
看了下别人的方法,用字符串替代了list,运行时间超过100%的java提交。
参考代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
String leaf1 = helper(root1);
String leaf2 = helper(root2);
return leaf1.equals(leaf2);
}
private String helper(TreeNode root) {
if(root == null) {
return "";
}
if(root.left == null && root.right == null) {
return ""+root.val;
}
String left = helper(root.left);
String right = helper(root.right);
return left+right;
}
}