Fork me on GitHub

101. 对称二叉树


递归解法

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)return true;
		return dfs(root.left,root.right);
	}
	public boolean dfs(TreeNode l, TreeNode r) {
		if(l==null||r==null) return l==null&&r==null;
		if(l.val!=r.val)return false;
		return dfs(l.left,r.right)&&dfs(l.right,r.left);
	}
}

递推解法

class Solution {
    public boolean isSymmetric(TreeNode root) {
    	if(root==null)return true;
    	Stack <TreeNode> stack1 = new Stack <TreeNode>();
    	Stack <TreeNode> stack2 = new Stack <TreeNode>();
    	TreeNode temp1 = root.left;
    	TreeNode temp2 = root.right;
    	while(temp1!=null||temp2!=null||!stack1.isEmpty()||!stack2.isEmpty()) {
    		while(temp1!=null&&temp2!=null) {
    			stack1.push(temp1);
    			temp1 = temp1.left;
    			stack2.push(temp2);
    			temp2 = temp2.right;
    		}
    		if(temp1!=null||temp2!=null)return false;
    		temp1 = stack1.pop();
    		temp2 = stack2.pop();
    		if(temp1.val!=temp2.val)
    			return false;
    		temp1 = temp1.right;
    		temp2 = temp2.left;
    	}
    	return true;
    }
}
posted @ 2019-08-13 20:48  cznczai  阅读(93)  评论(0编辑  收藏  举报