Written interview questions: Judgment of symmetric tree

     Originally published in:

20200104213843347.gif

 

 

      On Saturday, I was awakened by the construction outside. There was no such situation in the past. I don't know what they are doing. Today, let's talk about the judgment of symmetric trees.

 

     Over the years, I have been fooling my friends to BATH to promote the flow of talents, and I can also get some benefits by the way.

     Brother S is one of my goals for spoofing. Brother S came from a 985 civil engineering major. Later, he switched to a career as a programmer and went to T company for an interview. He came across such a problem (see the easy level problem in Leetcode):

 

 

 

       Let's analyze this problem. As shown in the figure below, assuming that both the left and right subtrees of root exist, the necessary and sufficient condition for root tree symmetry is: root.Left and root.Right are two symmetrical trees.

 

      How to judge that root.Left and root.Right are two symmetrical trees? Must and only need to meet the following three conditions:

      a. root.Left.Val = root.Right.Val, which is 3.

      b. The left subtree of root.Left and the right subtree of root.Right are symmetrical to each other, which is 2, -1 in the figure above.

      c. The right subtree of root.Left and the left subtree of root.Right are symmetrical to each other, namely 4, 9 in the figure above.

     

 

      Obviously, this is a recursive problem.

      Through analysis and disassembly, the original problem is self-solving. Not much to say, just go to the code:

func isSymmetric(root *TreeNode) bool {
    if root == nil {
        return true
    }

    if root.Left == nil && root.Right != nil {
        return false
    }

    if root.Left != nil && root.Right == nil {
        return false
    }

    return checkTwoSymmetric(root.Left, root.Right) 
}

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

    if p == nil && q != nil {
        return false
    }

    if p != nil && q == nil {
        return false
    }

    if p.Val == q.Val {
        return checkTwoSymmetric(p.Left, q.Right) && checkTwoSymmetric(p.Right, q.Left);
    }

    return false;
}

 

      Self-test was conducted on leetcode and passed. Similarly, we can also judge whether two trees are the same tree, the code is simpler, so I won't repeat it.

 

      If you encounter a problem, you must learn to decompose it, and then destroy each one. Finally, S brother’s heart is higher than the sky, he has ideals and pursuits. Congratulations to S brother for getting the offer of T company. I believe this is not the end.

 

Guess you like

Origin blog.csdn.net/stpeace/article/details/110419760