검지offer--서열화 두 갈래 나무

1906 단어

제목 설명/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.ArrayList; public class Solution { String Serialize(TreeNode root) { if(root==null) return ""; StringBuilder sb = new StringBuilder(); ArrayList<TreeNode> queue = new ArrayList<TreeNode>(); ArrayList<String> result = new ArrayList<String>(); queue.add(root); result.add(root.val+""); int low = 0; int high = 1; while(low<high){ TreeNode t = queue.get(low); if(t.left!=null){ result.add(t.left.val+""); queue.add(t.left); high++; }else{ result.add("#"); } if(t.right!=null){ result.add(t.right.val+""); queue.add(t.right); high++; }else{ result.add("#"); } low++; } int i; for(i=result.size()-1;i<result.size();i--){ if(!result.get(i).endsWith("#")) break; } for(int j=0;j<=i;j++){ sb.append(result.get(j)).append(","); } return sb.deleteCharAt(sb.length()-1).toString(); } TreeNode Deserialize(String str) { if(str.length()==0) return null; String[] chars = str.split(","); ArrayList<TreeNode> queue = new ArrayList<TreeNode>(); TreeNode t = new TreeNode(Integer.valueOf(chars[0])); queue.add(t); int low = 0; for(int i=0;i<chars.length && low<queue.size();){ t = queue.get(low); if(i+1<chars.length){ i++; TreeNode left = null; if(!("#".equals(chars[i]))){ left = new TreeNode(Integer.valueOf(chars[i])); queue.add(left); } t.left = left; } if(i+1<chars.length){ i++; TreeNode right = null; if(!"#".equals(chars[i])){ right = new TreeNode(Integer.valueOf(chars[i])); queue.add(right); } t.right = right; } low++; } return queue.get(0); } }


두 함수를 실현하십시오. 각각 서열화와 반서열화 두 갈래 나무에 쓰십시오

좋은 웹페이지 즐겨찾기