美文网首页
101. Symmetric Tree

101. Symmetric Tree

作者: hyhchaos | 来源:发表于2016-12-21 11:18 被阅读13次

Java ,中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        ArrayList<int[]> tmp=new ArrayList<int[]>();
        rec(root,tmp,0);
        for(int i=0;i<tmp.size();i++)
        {
            if(tmp.get(i)[0]!=tmp.get(tmp.size()-1-i)[0]||tmp.get(i)[1]!=tmp.get(tmp.size()-1-i)[1])
            return false;
        }
        return true;
        
    }
    
    public void rec(TreeNode root,List tmp,int level) {
        if(root==null) return;
        else
        {
            level++;
            rec(root.left,tmp,level);
            int[] m=new int[2];
            m[0]=root.val;
            m[1]=level;
            tmp.add(m);
            rec(root.right,tmp,level);
        }
    }
}

优解,Java

public boolean isSymmetric(TreeNode root) {
    return root==null || isSymmetricHelp(root.left, root.right);
}

private boolean isSymmetricHelp(TreeNode left, TreeNode right){
    if(left==null || right==null)
        return left==right;
    if(left.val!=right.val)
        return false;
    return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);
}

相关文章

网友评论

      本文标题:101. Symmetric Tree

      本文链接:https://www.haomeiwen.com/subject/ashqvttx.html