*LeetCode-Symmetric Tree

35 篇文章 0 订阅
22 篇文章 0 订阅

今天怎么状态这么不好,感觉这个题不简单啊,居然是easy。

看了答案才写出来。两种,recursive代码很简单,只是想清楚不容易,感觉怎么写helper要想明白。

 iterative 写了好久,总是出错,用stack实现,每次push一对对应位置上的node,即应该相等的node。push进去之前就判断这对的值是否相等,pop出来之后,对于这一对,要检查一下前提条件(是否都具有左右子,对应左右子的值是否相等)然后就push相应的两对,分别是 left.left 和 right.right, 以及left.right和 right.left。

recursive:

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

iterative:

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if ( root == null )
            return true;
        Stack <TreeNode> st = new Stack<TreeNode>();
        if ( root.left != null ){
            if ( root.right == null)
                return false;
            if ( root.left.val != root.right.val )
                return false;
            st.push(root.left);
            st.push(root.right);
        }
        else{ 
            if ( root.right != null)
                return false;
        }


        while ( !st.empty()){
            TreeNode rightc = st.pop();
            TreeNode leftc = st.pop();
            if ( rightc.left != null ){
                if ( leftc.right == null)
                    return false;
                if ( leftc.right.val != rightc.left.val )
                    return false;
                st.push(leftc.right);
                st.push(rightc.left);
            }
            else {
                if ( leftc.right != null)
                    return false;
            }
   
            
            if ( leftc.left != null ){
                if ( rightc.right == null)
                    return false;
                if ( leftc.left.val != rightc.right.val )
                    return false;
                st.push(leftc.left);
                st.push(rightc.right); 
            }
            else {
                if ( rightc.right != null)
                    return false;
            }
            
        }
        return true;
        
           
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值