94. 二叉树的中序遍历

这里写图片描述


c代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */

//访问节点并存储
void visit(struct TreeNode* root,int **result,int* returnSize){
    if(!*result){//如果空
        *result=(int *)malloc(sizeof(int));
    }else{
        //重新分配内存
        *result=(int *)realloc(*result,(*returnSize+1)*sizeof(int));
    }
    (*result)[(*returnSize)++]=root->val;
}

//中序
void inorder(struct TreeNode* root,int **result,int* returnSize){
    if(root){
        inorder(root->left,result,returnSize);
        visit(root,result,returnSize);
        inorder(root->right,result,returnSize);
    }
}

//中序遍历
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int *result=NULL;
    *returnSize=0;
    inorder(root,&result,returnSize);
    return result;
}

Java代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    // 访问节点并存储
    public void visit(TreeNode root, List<Integer> result) {
        // 在Java中这个函数实现起来就省事了很多,不用像C语言那样临时分配内存
        result.add(root.val);
    }

    // 中序
    public void inorder(TreeNode root, List<Integer> result) {
        if (root != null) {
            inorder(root.left, result);
            visit(root, result);
            inorder(root.right, result);
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        inorder(root, result);
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值