Leetcode: 二叉樹的中序遍歷
中序遍歷的流程:一直往左找,找到最左邊的元素訪問了之后,因為不存在左孩紙,所以訪問完之后,再訪問右子樹,當右子樹訪問完,說明該左節點訪問結束,就該回溯到上一個左節點,以此類推。
題目:
給定一個二叉樹,返回它的中序遍歷。
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
Python 實現
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
"""
思路:先往左訪問到底,然后訪問最左的第一個元素(不存在左孩子了),再去訪問他的右子樹,右子樹訪問完,回溯到上一個左孩子,進行訪問,
"""
result = []
stack = []
while True:
while root:
stack.append(root)
root = root.left # 一直往左走
if len(stack) == 0:
return result
root = stack.pop()
result.append(root.val) # 訪問最左邊的
root = root.right # 訪問最右邊的
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().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int *result = (int *)malloc(sizeof(int)*100);
struct TreeNode *stack[100];
int top = -1;
int i = 0;
while(true){
while(root){
stack[++top] = root;
root = root->left; //往左走到底,就可以訪問
}
if(top == -1){
*returnSize = i;
return result;
}
root = stack[top--]; //拿到最左邊的點,訪問
result[i++] = root->val;
root = root->right; //訪問完,就該訪問右邊的了。
}
}
