package Java6;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode{
public TreeNode(int val) {
this.val = val;
}
public int val;
public TreeNode left;
public TreeNode right;
}
public class Interview {
public List preorderTraversal(TreeNode root) {
List result = new ArrayList<>();
if (root == null)
return result;
result.add(root.val);
//遍历左子树
result.addAll(preorderTraversal(root.left));
result.addAll(preorderTraversal(root.right));
return result;
}
public List<Integer> InorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
result.addAll(InorderTraversal(root.left));
result.add(root.val);
result.addAll(InorderTraversal(root.right));
return result;
}
public List<Integer> PostorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
result.addAll(PostorderTraversal(root.left));
result.addAll(PostorderTraversal(root.right));
result.add(root.val);
return result;
}
public boolean isSameTree(TreeNode p,TreeNode q ){
if(p==null&&q==null){
return true;
}
if(p==null||q==null) {
return false;
}
if(p.val!=q.val){
return false;
}
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
public boolean isSubTree(TreeNode s,TreeNode t){
if(s==null&&t==null){
return true;
}
if(s==null||t==null){
return false;
}
boolean ret=false;
if(s.val==t.val){
ret=isSameTree(s, t);
}
if(!ret){
ret=isSubTree(s.left,t);
}
if(!ret){
ret=isSubTree(s.right,t);
}
return ret;
}
public int maxDepth(TreeNode root){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
int leftDepth =maxDepth(root.left);
int rightDepth=maxDepth(root.right);
return 1+(Math.max(leftDepth, rightDepth));
}
public boolean isBalanced(TreeNode root){
if(root==null){
return true;
}
if(root.left==null&&root.right==null){
return true;
}
int leftDepth=maxDepth(root.left);
int rightDepth=maxDepth(root.right);
if(leftDepth-rightDepth>1||leftDepth-rightDepth<-1){
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
public boolean isSymmetric(TreeNode root){
if(root==null){
return true;
}
return isMirror(root.left,root.right);
}
private boolean isMirror(TreeNode t1, TreeNode t2) {
if(t1==null && t2==null){
return true;
}
if(t1==null||t2==null){
return false;
}
if(t1.val!=t2.val){
return false;
}
return isMirror(t1.left,t2.right)&&isMirror(t1.right,t2.left);
}
public void levelOrder(TreeNode root){
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur= queue.poll();
System.out.print(cur.val+" ");
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
}
}
}