第58——对称的二叉树

229 阅读1分钟

题目:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路:

利用栈,先根的左右孩子进栈,然后栈不空做循环,出两个栈,判断出来的两个的值是否相等,若不等则返回false,否则让左的左孩子和右的右孩子,左的右孩子和右的左孩子一次进栈。

Java

package nowcoder;

import java.util.Stack;

public class S58_IsSymmetrical {
    public boolean isSymmetrical(TreeNode pNode){
        if (pNode == null)
            return true;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(pNode.left);
        stack.push(pNode.right);
        while (!stack.empty()){
            TreeNode p = stack.pop();//右孩子
            TreeNode q = stack.pop();//左孩子
            if (p == null && q == null)
                continue;
            if (p == null || q == null)
                return false;
            if (p.val != q.val)
                return false;
            stack.push(q.left);
            stack.push(p.right);
            stack.push(q.right);
            stack.push(p.left);
        }
        return true;
    }
    public static void main(String[] args){
        S58_IsSymmetrical s58 = new S58_IsSymmetrical();
        PrintTreeLayer p = new PrintTreeLayer();
        Integer[] array = {1, 2, 2, 3, 4, 4, 5};
        TreeNode root = p.arrayToTree(array, 0);
        System.out.println(s58.isSymmetrical(root));
    }
}

Python

import PrintTreeLayer
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class IsSymmetrical:
    def isSymmetrical(self, pRoot):
        if not pRoot:
            return True
        return self.compare(pRoot.left, pRoot.right)
    def compare(self, pRoot1, pRoot2):
        if not pRoot1 and not pRoot2:
            return True
        if not pRoot1 or not pRoot2:
            return False
        if pRoot1.val == pRoot2.val:
            if self.compare(pRoot1.left, pRoot2.right) and self.compare(pRoot1.right, pRoot2.left):
                return True
        return False
if __name__ == '__main__':
    test = IsSymmetrical()
    p = PrintTreeLayer.PrintTreeLayer()
    array = [1, 2, 2, 3, 4, 4, 3]
    root = p.arrayToTree(array, 0)
    print(test.isSymmetrical(root))