最近在刷leetcode,虽然还是很菜,但是我决定这学期刷完easy和medium!然后寒假继续刷然后就投简历找暑假实习啦。

而且这两天学的linux是关于线程管理,系统启动流程的。感觉还没有理解透,所以就没有写博客。我一定会补上的!!ORZ

递归一直是短板,所以就决定写几篇博客分析递归,方便以后复习。


 

题目:

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.


 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean leafSimilar(TreeNode root1, TreeNode root2) {
12         if(root1==null&&root2==null)
13             return true;
14         if(root1==null||root2==null)
15             return false;
16         StringBuilder leaf_t1=new StringBuilder();
17         StringBuilder leaf_t2=new StringBuilder();
18         getLeaves(leaf_t1,root1);
19         getLeaves(leaf_t2,root2);
20         return leaf_t1.toString().equals(leaf_t2.toString());
21     }
22     
23     private void getLeaves(StringBuilder sb,TreeNode root){
24         if(root==null)
25             return;
26         getLeaves(sb,root.left);
27         if(root.left==null && root.right==null){
28             sb.append(root.val);
29         }
30         getLeaves(sb,root.right);
31         return;
32     }
33 }

 

posted on 2018-09-08 18:03  孙好烦  阅读(226)  评论(0)    收藏  举报