🧮 Algo
数据结构与算法
双指针、回溯剪枝、图论与搜索
🎨 视觉封面LeetCode Invert Binary Tree
📅 2018-06-07·✍️ onecode·计算中...·⏱️ 2 分钟
#LeetCode#Python
Problem
Invert a binary tree.
Example:
Code
14 行
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
对树进行完全的左右节点交换
Python3
Python
39 行
# Invert a binary tree.
#
# Example:
#
# Input:
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# Output:
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
分析
很自然的想到了递归
💡 OneCoder 资源指引
所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI
🤝 技术交流与答疑
欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。
📚
猜你想读 · 相关文章推荐
算法与 LeetCode 专题 · 核心算法⏱️ 4 分钟
LeetCode Minimum Depth of Binary Tree
Problem Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest lea...
阅读全文 →
算法与 LeetCode 专题 · 核心算法⏱️ 4 分钟
LeetCode Path Sum
Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For...
阅读全文 →
算法与 LeetCode 专题 · 核心算法⏱️ 5 分钟
LeetCode Path Sum II
Problem Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum...
阅读全文 →
OneCoder (lihongzheshuai)
一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com
读者讨论与留言
💬 还没有读者留言,快来成为第一个讨论者吧!