Leetcoed--Binary Tree Inorder Traversal (二叉搜索树--中序遍历)
来源:互联网 发布:淘宝助理5.5官方版 编辑:程序博客网 时间:2024/06/15 21:28
题目:
给定一个二叉搜索树,求它的中序遍历结果
思路:
使用递归,给定一颗树,先遍历左子树,再读根,再遍历右子树。遍历左子树的方式可以再调用这个函数本身,经过多次递归调用,可以完成对给定树的中序遍历
代码:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ans = [] if not root: return ans else: self.dfs(root,ans) return ans def dfs(self,root,ans): if not root: return self.dfs(root.left,ans) ans.append(root.val) self.dfs(root.right,ans)
注意:python的类内函数参数self的作用:self指的是这个类对象本身,类似于c++的this,self参数python会自动给定,所以传递参数时不必要传self的值(也可以传对象名)。而函数定义时最好有self参数,方便递归调用,也方便读者阅读。
阅读全文
1 0
- Leetcoed--Binary Tree Inorder Traversal (二叉搜索树--中序遍历)
- LeetCode Binary Tree Inorder Traversal 中序遍历二叉树
- Binary Tree Inorder Traversal 二叉树的中序遍历
- 二叉树的中序遍历 Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal 二叉树的中序遍历
- 94.LeetCode Binary Tree Inorder Traversal(medium)[中序遍历二叉树 树的遍历]
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序遍历二叉树
- Binary Tree Inorder Traversal——二叉树的中序遍历
- LeetCode | Binary Tree Inorder Traversal(二叉树的中序遍历)
- Binary Tree Inorder Traversal 中序遍历二叉树 递归和非递归版
- LeetCode—***Binary Tree Inorder Traversal二叉树的中序遍历
- LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- LeetCode 94. Binary Tree Inorder Traversal(二叉树的中序遍历)
- Binary Tree Inorder Traversal 二叉树的中序遍历(迭代非递归版本)
- 【leetcode】94Binary Tree Inorder Traversal(非递归中序遍历二叉树)
- LeetCode 94 Binary Tree Inorder Traversal (中序遍历二叉树)
- 67.Binary Tree Inorder Traversal-二叉树的中序遍历(容易题)
- 图像分类——细粒度的概念
- 线性非线性光耦 传输特性
- JVM-栈帧
- Vue 中$els 的用法和理解
- 程序员-PM怎么让项目预估的时间更加准确
- Leetcoed--Binary Tree Inorder Traversal (二叉搜索树--中序遍历)
- 润乾报表5填报表中如何添加html代码
- VNC远程登录服务器(Ubuntu14.04)
- 课工场 “微服私访”项目学习(八)
- 牛郎织女都见面,而你却在吃狗粮---男士星座脱单指南
- 关于input file 的一些
- [日推荐] 『夜听零点』让温暖的声音伴你入眠
- mysql存储过程的三种循环
- MySQL编码修改--> 支持emoji表情