题目描述
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
思路题解
栈
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
stack:= []*TreeNode{}
var ans []int
for root!=nil || len(stack)>0{
for root!=nil{
stack=append(stack,root)
root=root.Left
}
root=stack[len(stack)-1]
ans=append(ans,root.Val)
stack=stack[:len(stack)-1]
root=root.Right
}
return ans
}
递归
很奇怪,上面这种写法就行,下面的就不行,然而测试用例是对的。等以后搞清楚了原因再来更新
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) (ans []int) {
var dfs func(node *TreeNode)
dfs=func(node *TreeNode){
if node.Left!=nil{
dfs(node.Left)
}
ans=append(ans,node.Val)
if node.Right!=nil{
dfs(node.Right)
}
return
}
if root==nil{
return nil
}
dfs(root)
return
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var ans []int
func dfs(root *TreeNode){
if root.Left!=nil{
dfs(root.Left)
}
ans=append(ans,root.Val)
if root.Right!=nil{
dfs(root.Right)
}
return
}
func inorderTraversal(root *TreeNode) []int {
if root!=nil{
dfs(root)
}
return ans
}
上面这个代码在提交后前面莫名多了个[1,3,2,1]
,但自己测试的时候是没有的