From cf6ec4f65a8ee43a15c29f0a380cfac5f809a8dd Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Tue, 18 May 2021 22:58:00 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 二叉树的迭代遍历 GO版本 --- problems/二叉树的迭代遍历.md | 102 +++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 2647616b..d228077b 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -163,7 +163,109 @@ Python: Go: +> 迭代法前序遍历 +```go +//迭代法前序遍历 +/** + type Element struct { + // 元素保管的值 + Value interface{} + // 内含隐藏或非导出字段 +} + +func (l *List) Back() *Element +前序遍历:中左右 +压栈顺序:右左中 + **/ +func preorderTraversal(root *TreeNode) []int { + if root == nil { + return nil + } + var stack = list.New() + stack.PushBack(root.Right) + stack.PushBack(root.Left) + res:=[]int{} + res=append(res,root.Val) + for stack.Len()>0 { + e:=stack.Back() + stack.Remove(e) + node := e.Value.(*TreeNode)//e是Element类型,其值为e.Value.由于Value为接口,所以要断言 + if node==nil{ + continue + } + res=append(res,node.Val) + stack.PushBack(node.Right) + stack.PushBack(node.Left) + } + return res +} +``` + +> 迭代法后序遍历 + +```go +//后续遍历:左右中 +//压栈顺序:中右左(按照前序遍历思路),再反转结果数组 +func postorderTraversal(root *TreeNode) []int { + if root == nil { + return nil + } + var stack = list.New() + stack.PushBack(root.Left) + stack.PushBack(root.Right) + res:=[]int{} + res=append(res,root.Val) + for stack.Len()>0 { + e:=stack.Back() + stack.Remove(e) + node := e.Value.(*TreeNode)//e是Element类型,其值为e.Value.由于Value为接口,所以要断言 + if node==nil{ + continue + } + res=append(res,node.Val) + stack.PushBack(node.Left) + stack.PushBack(node.Right) + } + for i:=0;i 迭代法中序遍历 + +```go +//迭代法中序遍历 +func inorderTraversal(root *TreeNode) []int { + rootRes:=[]int{} + if root==nil{ + return nil + } + stack:=list.New() + node:=root + //先将所有左节点找到,加入栈中 + for node!=nil{ + stack.PushBack(node) + node=node.Left + } + //其次对栈中的每个节点先弹出加入到结果集中,再找到该节点的右节点的所有左节点加入栈中 + for stack.Len()>0{ + e:=stack.Back() + node:=e.Value.(*TreeNode) + stack.Remove(e) + //找到该节点的右节点,再搜索他的所有左节点加入栈中 + rootRes=append(rootRes,node.Val) + node=node.Right + for node!=nil{ + stack.PushBack(node) + node=node.Left + } + } + return rootRes +} +```