Given binary trees, write a function to check if they is equal or not.
The binary trees is considered equal if they is structurally identical and the nodes has the same value.
Train of thought: just learned two fork tree, thought may want to separate traverse again compares, but to this question concrete realization has not experienced and the concrete code structure.
Reference code:
/* https://leetcode.com/problems/same-tree/#100 same treelevel:easygiven binary trees, write a function to check if T Hey is equal or not. The binary trees is considered equal if they is structurally identical and the nodes has the same value. Inspired by [@JohnWeiGitHub] (https://leetcode.com/discuss/3470/seeking-for-better-solution) and [@scott] (https:// Leetcode.com/discuss/22197/my-non-recursive-method) */import foundationclass Easy_100_same_tree {class Node {VA R Left:node? var right:node? var value:int init (Value:int, Left:node, Right:node?) {Self.value = value Self.left = left self.right = right}} t = O (n), average s = O (logn), worst s = O (n) Private class Func issametree_recursion (P p:node?, Q:node?), Bo OL {if p = = Nil | | q = NIL {return (P = = Nil && q = nil)} else {return P !. Value = = q!. Value && issametree (p:p?. Left Q:q?. left) && issametree (p:p?. Right, q:q? Right)}}//t = O (n), average s = O (logn), worst s = O (N) Private class func issametree_iteration (P p:n Ode?, Q:node?) Bool {if p = = Nil | | q = = NIL {return (P = = Nil && q = nil)} var stack_p : [Node] = [] var stack_q: [Node] = [] Stack_p.append (p!) Stack_q.append (q!) While stack_p.isempty = = False && Stack_q.isempty = = False {Let Tmp_p:node = Stack_p.removelast () Let Tmp_q:node = Stack_q.removelast () if tmp_p.value! = Tmp_q.value {return false } if Tmp_p.left! = nil {stack_p.append (tmp_p.left!) } if Tmp_q.left! = nil {stack_q.append (tmp_q.left!) If Stack_p.count! = Stack_q.count {return false} if tmp_p.right! = Nil {Stack_p.apPend (tmp_p.right!) } if Tmp_q.right! = nil {stack_q.append (tmp_q.right!) If Stack_p.count! = Stack_q.count {return false}} return stack_q.c Ount = = Stack_q.count} class func Issametree (P p:node, Q:node?), Bool {return issametree_iteration ( P:p, Q:q)}}
Summary: Time reasons, the code is not fully understood, the initialization of the tree is also different, leetcode on the AC, empty time to look back at the problem.
100.Same Tree (Swift to be solved)