首页 > 其他分享 >[Leetcode] 0101. 对称二叉树

[Leetcode] 0101. 对称二叉树

时间:2023-10-25 10:02:50浏览次数:45  
标签:right TreeNode val 0101 二叉树 left root1 Leetcode root2

101. 对称二叉树

题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。

 

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false

 

提示:

  • 树中节点数目在范围 [1, 1000]
  • -100 <= Node.val <= 100

 

进阶:你可以运用递归和迭代两种方法解决这个问题吗?

解法

方法一:递归

我们设计一个函数 \(dfs(root1, root2)\),用于判断两个二叉树是否对称。答案即为 \(dfs(root, root)\)。

函数 \(dfs(root1, root2)\) 的逻辑如下:

  • 如果 \(root1\) 和 \(root2\) 都为空,则两个二叉树对称,返回 true
  • 如果 \(root1\) 和 \(root2\) 中只有一个为空,或者 \(root1.val \neq root2.val\),则两个二叉树不对称,返回 false
  • 否则,判断 \(root1\) 的左子树和 \(root2\) 的右子树是否对称,以及 \(root1\) 的右子树和 \(root2\) 的左子树是否对称,这里使用了递归。

时间复杂度 \(O(n)\),空间复杂度 \(O(n)\)。其中 \(n\) 是二叉树的节点数。

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(root1, root2):
            if root1 is None and root2 is None:
                return True
            if root1 is None or root2 is None or root1.val != root2.val:
                return False
            return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)

        return dfs(root, root)

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return dfs(root, root);
    }

    private boolean dfs(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {
            return true;
        }
        if (root1 == null || root2 == null || root1.val != root2.val) {
            return false;
        }
        return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
    }
}

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        function<bool(TreeNode*, TreeNode*)> dfs = [&](TreeNode* root1, TreeNode* root2) -> bool {
            if (!root1 && !root2) return true;
            if (!root1 || !root2 || root1->val != root2->val) return false;
            return dfs(root1->left, root2->right) && dfs(root1->right, root2->left);
        };
        return dfs(root, root);
    }
};

Go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSymmetric(root *TreeNode) bool {
	var dfs func(*TreeNode, *TreeNode) bool
	dfs = func(root1, root2 *TreeNode) bool {
		if root1 == nil && root2 == nil {
			return true
		}
		if root1 == nil || root2 == nil || root1.Val != root2.Val {
			return false
		}
		return dfs(root1.Left, root2.Right) && dfs(root1.Right, root2.Left)
	}
	return dfs(root, root)
}

TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

const dfs = (root1: TreeNode | null, root2: TreeNode | null) => {
    if (root1 == root2) {
        return true;
    }
    if (root1 == null || root2 == null || root1.val != root2.val) {
        return false;
    }
    return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
};

function isSymmetric(root: TreeNode | null): boolean {
    return dfs(root.left, root.right);
}

Rust

// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
    fn dfs(root1: &Option<Rc<RefCell<TreeNode>>>, root2: &Option<Rc<RefCell<TreeNode>>>) -> bool {
        if root1.is_none() && root2.is_none() {
            return true;
        }
        if root1.is_none() || root2.is_none() {
            return false;
        }
        let node1 = root1.as_ref().unwrap().borrow();
        let node2 = root2.as_ref().unwrap().borrow();
        node1.val == node2.val
            && Self::dfs(&node1.left, &node2.right)
            && Self::dfs(&node1.right, &node2.left)
    }

    pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
        let node = root.as_ref().unwrap().borrow();
        Self::dfs(&node.left, &node.right)
    }
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
impl Solution {
    pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
        let root = root.unwrap();
        let mut node = root.as_ref().borrow_mut();
        let mut queue = VecDeque::new();
        queue.push_back([node.left.take(), node.right.take()]);
        while let Some([root1, root2]) = queue.pop_front() {
            if root1.is_none() && root2.is_none() {
                continue;
            }
            if root1.is_none() || root2.is_none() {
                return false;
            }
            if let (Some(node1), Some(node2)) = (root1, root2) {
                let mut node1 = node1.as_ref().borrow_mut();
                let mut node2 = node2.as_ref().borrow_mut();
                if node1.val != node2.val {
                    return false;
                }
                queue.push_back([node1.left.take(), node2.right.take()]);
                queue.push_back([node1.right.take(), node2.left.take()]);
            }
        }
        true
    }
}

...



标签:right,TreeNode,val,0101,二叉树,left,root1,Leetcode,root2
From: https://www.cnblogs.com/yege/p/17786423.html

相关文章

  • LeetCode 283. 移动零
    移动零题目链接283.移动零给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。请注意,必须在不复制数组的情况下原地对数组进行操作。示例1:输入:nums=[0,1,0,3,12]输出:[1,3,12,0,0]示例2:输入:nums=[0]输出:[0]题......
  • 代码随想训练营第十四天(Python)| 层序遍历 10 、● 226.翻转二叉树 、101.对称二叉树 2
    层序遍历1、迭代法,使用队列classSolution:deflevelOrder(self,root:Optional[TreeNode])->List[List[int]]:res=[]ifrootisNone:returnresqueue=[root]whilequeue:n=len(queue)......
  • LeetCode 1089. 复写零
    复写零题目链接1089.复写零给你一个长度固定的整数数组arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。注意:请不要在超过该数组长度的位置写入元素。请对输入的数组就地进行上述修改,不要从函数返回任何东西。示例1:输入:arr=[1,0,2,3,0,4,5,0]输......
  • LeetCode 202. 快乐数
    快乐数题目链接202.快乐数编写一个算法来判断一个数n是不是快乐数。「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为1,也可能是无限循环但始终变不到1。如果这个过程结果为1,那么这个数就是快乐......
  • LeetCode 11. 盛最多水的容器
    盛水最多的容器题目链接11.盛最多水的容器给定一个长度为n的整数数组height。有n条垂线,第i条线的两个端点是(i,0)和(i,height[i])。找出其中的两条线,使得它们与x轴共同构成的容器可以容纳最多的水。返回容器可以储存的最大水量。**说明:**你不能倾斜容器......
  • LeetCode 611. 有效三角形的个数
    有效三角形的个数题目链接611.有效三角形的个数给定一个包含非负整数的数组nums,返回其中可以组成三角形三条边的三元组个数。示例1:输入:nums=[2,2,3,4]输出:3解释:有效的组合是:2,3,4(使用第一个2)2,3,4(使用第二个2)2,2,3示例2:输入:nums=[4,2,......
  • [Leetcode] 0100. 相同的树
    100.相同的树题目描述给你两棵二叉树的根节点p和q,编写一个函数来检验这两棵树是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例1:输入:p=[1,2,3],q=[1,2,3]输出:true示例2:输入:p=[1,2],q=[1,null,2]输出:false示例3:......
  • 二叉树遍历(先序、中序、后序)
    学习二叉树遍历(先序、中序、后序)的相关方法二叉树有多种遍历方法,有层次遍历、深度优先遍历、广度优先遍历等。本文只涉及二叉树的先序、中序、后序的递归和非递归遍历。涉及到的代码都用Java编写,可了解其流程。首先给出二叉树节点类:树节点:classTreeNode{intval;......
  • C++算法:二叉树的序列化与反序列化
    #题目序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列/反序列化算法执行逻......
  • LeetCode Day13 239&347
    //利用双端队列手动实现单调队列/***用一个单调队列来存储对应的下标,每当窗口滑动的时候,直接取队列的头部指针对应的值放入结果集即可*单调队列类似(tail-->)3-->2-->1-->0(-->head)(右边为头结点,元素存的是下标)*/239. 滑动窗口最大值classSolution{......