zoukankan      html  css  js  c++  java
  • 二叉树的中序遍历

    题目描述:

    给定一个二叉树,返回它的中序 遍历。

    输入: [1,null,2,3]
       1
        
         2
        /
       3
    
    输出: [1,3,2]
    //go
    //* Definition for a binary tree node.
    type TreeNode struct {
     Val int
     Left *TreeNode
     Right *TreeNode
    }
    
    var res []int
    
    func inorderTraversal(root *TreeNode) []int {
        res = make([]int, 0)
        inorder(root)
        return res
    }
    
    func inorder(root *TreeNode) {
        if root != nil {
            inorder(root.Left) 
            res = append(res, root.Val)
            inorder(root.Right)
        }
    }

    方法二:遍历

     

    其核心思想如下:

    • 使用颜色标记节点的状态,新节点为白色,已访问的节点为灰色。
    • 如果遇到的节点为白色,则将其标记为灰色,然后将其右子节点、自身、左子节点依次入栈。
    • 如果遇到的节点为灰色,则将节点的值输出。

    如要实现前序、后序遍历,只需要调整左右子节点的入栈顺序即可。

    //go
    
    type ColorNode struct {
     node *TreeNode
     color string
    }
    
    func inorderTraversal(root *TreeNode) []int {
     if root == nil {
      return []int{}
     }
     var res []int
     var stack []*ColorNode
     stack = append(stack, &ColorNode{root, "white"})
     var cn *ColorNode
    
     for len(stack) != 0 {
      cn = stack[len(stack)-1]
      stack = stack[:len(stack)-1] // 以上两句等同于 cn = stack.pop() ,别忘了加这句
      if cn.color == "white" {
       // 因为栈是先进后出,所以中序是 右-根-左 的顺序添加
       if cn.node.Right != nil {
        stack = append(stack, &ColorNode{cn.node.Right,"white"})
       }
       stack = append(stack,&ColorNode{cn.node, "gray"})
       if cn.node.Left != nil {
        stack = append(stack, &ColorNode{cn.node.Left, "white"})
       }
      }else {
       res = append(res, cn.node.Val)
      }
     }
    
     return res
    }
    

      地址:https://mp.weixin.qq.com/s/1p7ed_PwC_ctIOW8sFJ-nw

     

     

     

  • 相关阅读:
    算法学习概述(2016.6)
    java异常和错误类总结(2016.5)
    java string 细节原理分析(2016.5)
    MySQL 5.7.18 解压版安装
    Struts2的<s:date>标签使用详解[转]
    jprofile查看hprof文件[转]
    iBatis的Settings节点参数详解[转]
    window.open、window.showModalDialog和window.showModelessDialog 的区别[转]
    oracle 字典表查询
    oracle 表空间操作
  • 原文地址:https://www.cnblogs.com/smallleiit/p/13444192.html
Copyright © 2011-2022 走看看