C/C++教程

对称二叉树 · symmetric binary tree

本文主要是介绍对称二叉树 · symmetric binary tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

复习了还是不会的地方:分为主从函数,主函数中只需要判断第一个左右子树是否相等
isSymmetricHelper(root.left, root.right);

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        //corner case
        if (root == null) {
            return true;
        }
        return isSymmetricHelper(root.left, root.right);
    }
    
    public boolean isSymmetricHelper(TreeNode left, TreeNode right) {
        //all null
        if (left == null && right == null) {
            return true;
        }
        //one null
        if (left == null || right == null) {
            return false;
        }
        //not same 
        if (left.val != right.val) {
            return false;
        }
        //same
        return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left);
        //don't forget the function name
    }
}
View Code

 






这篇关于对称二叉树 · symmetric binary tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!