文章 224
评论 6
浏览 200761
Tree - 94. Binary Tree Inorder Traversal

Tree - 94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1

2
/
3
Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

思路:

二叉树的中序遍历,先访问左子树然后中间节点然后右子树。迭代也是使用list容器来充当栈

代码:

go :

/**

 * Definition for a binary tree node.

 * type TreeNode struct {

 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// recursive
/*func inorderTraversal(root *TreeNode) []int {
    var res []int
    
    recursive(root, &res)
    
    return res
}

func recursive(root * TreeNode, res *[]int) {
    if root == nil {
        return
    }
    
    recursive(root.Left, res)
    *res = append(*res, root.Val)
    recursive(root.Right, res)
}
*/

// iteratively
func inorderTraversal(root *TreeNode) []int {

    var res []int 
    var stack []*TreeNode

    cur := root 
    for cur != nil || len(stack) != 0 {
        for cur != nil {
            stack = append(stack, cur)
            cur = cur.Left
        }
        
        // 走到最左
        cur = stack[len(stack) - 1]
        stack = stack[:len(stack) - 1]
        res= append(res, cur.Val)
        cur = cur.Right
    }
    
    return res
}

标题:Tree - 94. Binary Tree Inorder Traversal
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/15/1565882454803.html

Nothing just happens, it's all part of a plan.

取消