其他分享
首页 > 其他分享> > 递归 二叉树前序 中序 后序遍历

递归 二叉树前序 中序 后序遍历

作者:互联网

 

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func inorderTraversal(root *TreeNode) []int {
	if root == nil {
		return nil
	}
	l := []int{}
	l = append(l, inorderTraversal(root.Left)...)
	l = append(l, root.Val)
	l = append(l, inorderTraversal(root.Right)...)
	return l
}

func preorderTraversal(root *TreeNode) []int {
	if root == nil {
		return nil
	}
	l := []int{}
	l = append(l, root.Val)
	l = append(l, preorderTraversal(root.Left)...)
	l = append(l, preorderTraversal(root.Right)...)
	return l
}

func postorderTraversal(root *TreeNode) []int {
	if root == nil {
		return nil
	}
	l := []int{}
	l = append(l, postorderTraversal(root.Left)...)
	l = append(l, postorderTraversal(root.Right)...)
	l = append(l, root.Val)
	return l
}

  

 

标签:return,nil,int,中序,二叉树,TreeNode,root,前序,append
来源: https://www.cnblogs.com/rsapaper/p/16175900.html