-
[LeetCode] 897. Increasing Order Search Tree c++Coding Test/LeetCode 2022. 9. 27. 12:49728x90
- 문제
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
이진탐색트리의 값들을 node.right로 오름차순으로 정렬하는 문제이다.
주어진 이진탐색트리들은 node.left → node.val → node.right 순으로 값들이 오름차순으로 정렬되어 있다.
- 문제 해결
1. root노드의 left 먼저 탐색
2. 최하위 까지 탐색했다면 ans노드의 right에 root값을 저장
3. ans노드를 right로 옮긴다.
4. root노드의 right탐색
void inorder(TreeNode*& ans, TreeNode* root){ if(!root){ return; } inorder(ans, root->left); ans->right = new TreeNode(root->val); ans = ans->right; inorder(ans, root->right); } TreeNode* increasingBST(TreeNode* root) { TreeNode* temp; TreeNode* ans = new TreeNode(); temp = ans; inorder(ans, root); return temp->right; }
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 1480. Running Sum of 1d Array c++ (0) 2022.10.10 [LeetCode] 1929. Concatenation of Array c++ (0) 2022.10.10 [LeetCode] 617. Merge Two Binary Trees c++ (0) 2022.09.27 [LeetCode] 2331. Evaluate Boolean Binary Tree c++ (0) 2022.09.26 [LeetCode] 938. Range Sum of BST c++ (0) 2022.09.26