leetcode-tree-94-Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

Binary Tree Inorder Traversal
中序遍历二叉树

注意二叉树并不是左节点小于父节点,右节点大于父节点,二叉搜索树才符合(BST)

  • Example:

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

Output: [1,3,2]

  • 解法一,递归
// recursive,中序遍历
function inorderTraversal(root,arr = []){
    if(root){
        inorderTraversal(root.left)
        arr.push(root.val)
        inorderTraversal(root.right)

    }
    return arr

}
  • 解法二,迭代
function inorderTraversal(root){
    const arr = []
    const stack = []
    let node = root;

    while(node || stack.lenght){
        while(node){
            stack.push(node.left)
            node = node.left
        }

        node = stack.pop() //出栈
        arr.push(node)
        node = node.right
    }
    return arr
}

你可能感兴趣的:(leetcode-tree-94-Binary Tree Inorder Traversal)