树的遍历 | 翻转二叉树
生活随笔
收集整理的這篇文章主要介紹了
树的遍历 | 翻转二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Invert a binary tree.
Example:Input:4/ \2 7/ \ / \ 1 3 6 9 Output:4/ \7 2/ \ / \ 9 6 3 1思路1 遞歸:
把左子樹和右子樹進行交換。交換完之后,再去遞歸翻轉左子樹和右子樹
class Solution(object):def invertTree(self, root):if root:root.left,root.right = root.right,root.leftself.invertTree(root.left)self.invertTree(root.right)return root思路2 遍歷
換父節點的時候,把子節點存下來,然后換完父節點了,就去換子點的。
class Solution(object):def invertTree(self, root):node = rootqueue = [root]while len(queue):root = queue.pop(-1)if root:root.left,root.right = root.right,root.leftif root.left:queue.append(root.left)if root.right:queue.append(root.right)return node轉載于:https://www.cnblogs.com/xmxj0707/p/10381201.html
總結
以上是生活随笔為你收集整理的树的遍历 | 翻转二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中级之网络数据解析一之Js
- 下一篇: Shell的 for 循环小例子