Skip to content

Latest commit

 

History

History
35 lines (28 loc) · 564 Bytes

same-tree.md

File metadata and controls

35 lines (28 loc) · 564 Bytes

Code

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func isSameTree(p *TreeNode, q *TreeNode) bool {
	if p == nil && q == nil {
		return true
	}

	if p == nil || q == nil {
		return false
	}

	if p.Val != q.Val {
		return false
	}

	return isSameTree(p.Right, q.Right) && isSameTree(p.Left, q.Left)
}

Solution in mind

  • Recursively verify if nodes of tree are same.
  • Above condition fails if only one of two node exists, or values vary.