11package com .leetcode .trees ;
22
3+ import java .util .LinkedList ;
4+ import java .util .Queue ;
5+
36import static org .junit .Assert .assertTrue ;
47
58/**
@@ -63,6 +66,42 @@ private static boolean isSymmetric(TreeNode leftRoot, TreeNode rightRoot) {
6366 return isSymmetric (leftRoot .left , rightRoot .right ) && isSymmetric (leftRoot .right , rightRoot .left ) && leftRoot .val == rightRoot .val ;
6467 }
6568
69+ /**
70+ * Time Complexity: O(n) Because we traverse the entire input tree once, the total run time is O(n), where n is the
71+ * total number of nodes in the tree.
72+ * Space Complexity: There is additional space required for the search queue. In the worst case, we have to
73+ * insert O(n) nodes in the queue. Therefore, space complexity is O(n).
74+ * Runtime: <a href="https://leetcode.com/submissions/detail/246708370/">1 ms</a>.
75+ *
76+ * @param root
77+ * @return
78+ */
79+ public static boolean isSymmetricIterative (TreeNode root ) {
80+ if (root == null || (root .left == null && root .right == null )) return true ;
81+ if (root .left == null || root .right == null ) return false ;
82+
83+ Queue <TreeNode > queue = new LinkedList <>();
84+ queue .add (root .left );
85+ queue .add (root .right );
86+
87+ while (!queue .isEmpty ()) {
88+ TreeNode t1 = queue .poll ();
89+ TreeNode t2 = queue .poll ();
90+
91+ if (t1 == null && t2 == null ) continue ;
92+ if (t1 == null || t2 == null ) return false ;
93+ if (t1 .val != t2 .val ) return false ;
94+
95+ // enqueue left and then right child of t1 but do the opposite for t2
96+ queue .add (t1 .left );
97+ queue .add (t2 .right );
98+ queue .add (t1 .right );
99+ queue .add (t2 .left );
100+ }
101+
102+ return true ;
103+ }
104+
66105 public static void main (String [] args ) {
67106 TreeNode root = new TreeNode (1 );
68107 root .left = new TreeNode (2 );
@@ -73,5 +112,6 @@ public static void main(String[] args) {
73112 root .right .right = new TreeNode (4 );
74113
75114 assertTrue (isSymmetric (root ));
115+ assertTrue (isSymmetricIterative (root ));
76116 }
77117}
0 commit comments