树的操作——python
来源:互联网 发布:mmdriver.inf修复软件 编辑:程序博客网 时间:2024/06/02 06:26
二叉树的最大节点
在二叉树中寻找值最大的节点并返回。
样例
给出如下一棵二叉树:
1 / \ -5 2 / \ / \0 3 -4 -5
返回值为 3
的节点。
解析:树的操作,许多都用到了递归思想,这个问题可以分解成,找到左子树的最大节点与右子树的最大节点。不断递归来找即可。
class Solution: # @param {TreeNode} root the root of binary tree # @return {TreeNode} the max node def maxNode(self, root): # Write your code here if root == None: return 0 maxLeft=max(root.val,self.maxNode(root.left)) maxRight=max(root.val,self.maxNode(root.right)) return max(maxLeft,maxRight)
二叉树的中序遍历
给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
#Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, Noneclass Solution: """ @param root: The root of binary tree. @return: Inorder in ArrayList which contains node values. """ def __init__(self): self.result = [] def inorderTraversal(self, root): # write your code here if root is None: return [] if root: self.inorderTraversal(root.left) self.result.append(root.val) self.inorderTraversal(root.right) if len(self.result) == 0: return [] else: return self.result
树的广度优先遍历(Python)。
# python写的树的广度优先算法,使用队列这种数据结构。def level_queue(root): if root is None: return my_queue=[] node=root my_queue.append(node) while my_queue: node=my_queue.pop(0) print(node.elem) if node.lchild is not None: my_queue.append(node.lchild) if node.rchild is not None: my_queue.append(node.rchild)
树的深度优先遍历(Python):
#树的深度优先遍历,使用递归遍历def depth_tree(tree_node): if tree_node is not None: print(tree_node._data) if tree_node._left is not None: return depth_tree(tree_node._left) if tree_node._right is not None: return depth_tree(tree_node._right)
0 0
- 树的操作——python
- python字符串的操作——python cookbook
- python学习—Day26—python的mysql操作
- Python—list操作
- Python—切片操作
- Python——目录操作
- Python——字符串操作
- Python——列表操作
- python——操作Redis
- Python——tuple操作
- Python——List操作
- Python——切片操作
- python——文件操作
- python——数据操作
- python——操作Redis
- python整理八——list的简单操作
- 20.python——序列的常用操作
- Python笔记4——文件的操作
- 实现网页同时只能有一个账号登录
- C++作业5
- html文字居中对齐显示
- Discuz!论坛教程之发贴机用&#x开头的字符绕过关键字的解决方法
- J--company
- 树的操作——python
- python基础_总结
- POJ
- Eclipse中Spring环境配置以及跑个Helloworld
- 使用Gradle构建EhCache3的Eclipse环境
- Android studio 类显示为方框不是圆圈
- 交叉编译 glib
- win 10 Ubuntu 子系统小记录
- 每天一个Linux命令:rm