[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,2,3]組成的二叉樹時,遍歷結果為[1,3,2]

方法

中序遍歷二叉樹,如果不用遞歸的方式,同樣需要借助棧。
將當前節點壓棧,然后將當前節點指向左子節點壓棧,循環直至左節點為空。然后從棧里取出節點,同時取出節點值。然后將當前節點指向右子節點,若當前節點不為空,循環開始的過程。直至當前節點為空并且棧為空的時候,退出循環。

c代碼
#include <assert.h>
#include <stdlib.h>

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().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    struct TreeNode* node;
    struct TreeNode** nodes = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * 1000);
    node = root;
    int nodesTop = 0;
    int* vals = (int *)malloc(sizeof(int) * 1000);
    int valsTop = 0;
    while(node!=NULL || nodesTop!=0) {
        while(node != NULL) {
            nodes[nodesTop++] = node;
            node = node->left;
        }
        node = nodes[--nodesTop];
        vals[valsTop++] = node->val;
        node = node->right;
    }
    *returnSize = valsTop;
    return vals;
}

int main() {
    struct TreeNode* root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    root->val = 1;
    struct TreeNode* node1_2 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    node1_2->val = 2;
    root->left = NULL;
    root->right = node1_2;
    struct TreeNode* node2_3 = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    node2_3->val = 3;
    node1_2->left = node2_3;
    node1_2->right = NULL;
    node2_3->left = NULL;
    node2_3->right = NULL;

    int returnSize = 0;
    int* vals = inorderTraversal(root, &returnSize);
    assert(returnSize == 3);
    assert(vals[0] == 1);
    assert(vals[1] == 3);
    assert(vals[2] == 2);

    return 0;
}
擴展

前序遍歷二叉樹
[LeetCode]144. Binary Tree Preorder Traversal

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容