Easy to read code which contains XOR


  • 0
    N
        public bool IsSymmetric(TreeNode root) 
        {
            if(root==null)
                return true;
            
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();//init stack. actually you can use queue, does not matter.
            nodeStack.Push(root.left);
            nodeStack.Push(root.right);
            
            while(nodeStack.Count>0)
            {
                TreeNode left = nodeStack.Pop();
                TreeNode right = nodeStack.Pop();
                
                if(left!=null&&right!=null) //both of them not null
                {
                    if(left.val!=right.val)
                        return false;
                    
                    nodeStack.Push(left.left);
                    nodeStack.Push(right.right);
                    nodeStack.Push(left.right);
                    nodeStack.Push(right.left);
                }
                else if(left==null^right==null) // xor being null
                {
                    return false;
                }
                
            }
            
            return true;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.