中序遍历二叉树

vector<int> inorderTraversal(TreeNode* root) {
    vector<int> inorderTraversalElems;

    function<void(TreeNode*& node)> traversal;
    traversal = [&](TreeNode*& node)
    {
        if (node == nullptr) {
            return;
        }

        traversal(node->left);
        inorderTraversalElems.push_back(node->val);
        traversal(node->right);
    };

    traversal(root);
    return inorderTraversalElems;
}
时间: 2024-08-09 19:42:13

中序遍历二叉树的相关文章

LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)

Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively?中序遍历二叉树,递归遍历当然很容易,题目还要求不用递归,下面给出两种方法: 递归: 1 /**

中序遍历二叉树+O(1)空间

问题描述 中序遍历二叉树时,很简单,需要加上递归就可以优雅地实现了.当然,使用递归的话,函数调用栈的空间就会达到O(log n).那么有什么方式,可以使得中序遍历二叉树的复杂度为O(1)呢? 问题分析 既然要保证O(1)复杂度,那么就不能使用递归调用了.目标方案应该是使用while或for循环的方式.下面借用一张图来解释(来源:http://www.2cto.com/kf/201402/277873.html): 如图所示,需要在多个节点(right指针为空),设置指针指向父节点.这样在遍历的时

完全二叉树的链式存储结构的转化 &amp; 非递归中序遍历二叉树

1 /* 2 * 二叉树 3 * 4 * (将完全二叉树的数组形式改为链表形式) 5 * 6 * 1 7 * 2 3 8 * 4 5 6 7 9 * 8 10 * 11 */ 12 #include <iostream> 13 #define MAX 10 14 using namespace std; 15 16 typedef struct btnode{ 17 int data; 18 struct btnode * lchild; 19 struct btnode * rchild;

Leetcode 94. Binary Tree Inorder Traversal (中序遍历二叉树)

Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree [1,null,2,3], 1 2 / 3 return [1,3,2]. Note: Recursive(递归) solution is trivial, could you do it iteratively(迭代)? 思路: 解法一:用递归方法很简单, (1)如果root为空,则返回NU

LeetCode 94 Binary Tree Inorder Traversal (中序遍历二叉树)

Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree [1,null,2,3], 1 2 / 3 return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively? 题目链接:https://leetcode.com/problems/binary-t

【中级算法】10.中序遍历二叉树

题目: 给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 解题算法: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right

很简洁的前序遍历和中序遍历二叉树代码(递归实现)

void preOrder(BinTree *root) //递归前序遍历 { if(root!=NULL) { cout<<root->data<<" "; preOrder1(root->lchild); preOrder1(root->rchild); } } void inOrder1(BinTree *root) //递归中序遍历 { if(root!=NULL) { inOrder1(root->lchild); cout&l

【数据结构】 非递归前中后序遍历二叉树

数据结构学的递归了,深入了解后写一个三序非递归的版本. //测试数据:abd##eg##h##c#f## #include <cstdio> #include <iostream> typedef char ElemType; typedef struct Node { ElemType elem; struct Node *lchild,*rchild; }Node,*BiTree; typedef struct{ BiTree *base; BiTree *top; int s

c之二叉树链表操作---建立、(递归)前序遍历、中序遍历、后序遍历

[二叉树链表] 1.节点定义: typedef struct node{ int data; struct node*lchild,*rchild; }Tree,*BiTree; 2.创建二叉树: BiTree creat_Tree(BiTree root,int num){//建立二叉树 if(root==NULL) { root=(Tree *)malloc(sizeof(Tree)); if(root==NULL) { printf("no memory available\n"