Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Binary Tree Inorder Traversal[E,Stack,Tree,Depth-First Search,Binary Tree]

eatplaylove 2024. 7. 31. 12:35

https://leetcode.com/problems/binary-tree-inorder-traversal/description/

Given the root of a binary tree, return the inorder traversal of its nodes' values.

 

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

굉장히 기초적인 것이라고 생각했던 부분들인데 모르겠다

아 짜증난다..

 

1. Python

# Recursive
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        # Recursive
        ans = []
        
        def inorder(root):
            if not root : return None
            inorder(root.left)
            ans.append(root.val)
            inorder(root.right)

        inorder(root)
        return ans

 

- Stack + iteration

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        s = []

        while root or s:
            while root:
                s.append(root)
                root = root.left
            
            root = s.pop()
            ans.append(root.val)

            root = root.right
        
        return ans

눈으로 대놓고 보면서 따라가도 이해가 어려운 영역

 

2. C

 

- Recursive

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void help(struct TreeNode* root,int* ans, int* returnSize){
    if(!root) return;

    help(root->left,ans,returnSize);
    ans[(*returnSize)++] = root->val;
    help(root->right,ans,returnSize);
    return;
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int* ans = (int*)malloc(100*sizeof(int));
    *returnSize = 0;
    help(root,ans,returnSize);
    return ans;
}

 

- Iteration

 

C는 Stack 구조부터 싸그리 재적립이 필요해서 Skip.. 역시 Container 쪽에선 약하다

 

 

3. C++

 

- Recursive

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        help(root,ans);
        return ans;
    }

    void help(TreeNode* root,vector<int>& ans){
        if(!root) return;
        
        help(root->left,ans);
        ans.push_back(root->val);
        help(root->right,ans);
    }
};

 

- Iteration

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> s;
        vector<int> ans;

        while(root || !s.empty()){
            while(root){
                s.push(root);
                root = root->left;
            }
            TreeNode* curr = s.top();
            s.pop();
            ans.push_back(curr->val);
            root = curr->right;
        }
        return ans;
    }
};

 

재야의 고수 문제들이 너~무 많다 ㅠ