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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章