question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
binary-tree-preorder-traversal | javascript stack 98% runtime, step by step | javascript-stack-98-runtime-step-by-step-w8rj | For anyone (new to algo/ds) who\'s beaten by this, here\'s an step by step explanation:\n\n\ntree:\n 1\n 2 3\n4 5 6 7\n\n1st iteration:\nstack: [1]\n\n2 | seanwth | NORMAL | 2020-02-25T17:11:42.947739+00:00 | 2020-02-25T17:11:42.947778+00:00 | 1,840 | false | For anyone (new to algo/ds) who\'s beaten by this, here\'s an step by step explanation:\n\n```\ntree:\n 1\n 2 3\n4 5 6 7\n\n1st iteration:\nstack: [1]\n\n2nd iteration:\ncurrent node = stack pop last element = 1\ncurrent node:\n 1\n 2 3\nstack push right of current node first then followed by left \nstack: [3, 2]\n\n3rd iteration:\ncurrent node = stack pop last element = 2\ncurrent node:\n 2\n 4 5\nstack push right current node first then followed by left \nstack: [3, 5, 4]\n\n4th iteration:\ncurrent node = stack pop last element = 4\ncurrent node:\n 4\nnull null\nstack push right current node first then followed by left \nstack: [3, 5]\n\n5th iteration:\ncurrent node = stack pop last element = 5\ncurrent node:\n 5\nnull null\nstack push right current node first then followed by left \nstack: [3]\n\n6th iteration:\ncurrent node = stack pop last element = 3\ncurrent node:\n 3\n6 7\nstack push right current node first then followed by left \nstack: [7, 6]\n\n7th iteration:\ncurrent node = stack pop last element = 6\ncurrent node:\n 6\nnull null\nstack push right current node first then followed by left \nstack: [7]\n\n8th iteration:\ncurrent node = stack pop last element = 6\ncurrent node:\n 7\nnull null\nstack push right current node first then followed by left \nstack: []\nstack.length === 0, false thereby terminating the for loop\n```\n\n**Full code:**\n```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nvar preorderTraversal = function(root) {\n if (!root) {\n return []\n }\n \n let stack = [root]\n let arr = []\n \n while (stack.length) {\n let curr = stack.pop()\n arr.push(curr.val)\n \n if (curr.right) {\n stack.push(curr.right)\n }\n \n if (curr.left) {\n stack.push(curr.left)\n }\n }\n \n return arr\n};\n``` | 21 | 0 | ['Stack', 'Iterator', 'JavaScript'] | 7 |
binary-tree-preorder-traversal | Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, Python3) || Recursive || Iterative | easy-0-ms-100-fully-explained-java-c-pyt-8dhu | Java Solution (Iterative Approach Using Stack):\nRuntime: 1 ms, faster than 93.68% of Java online submissions for Binary Tree Preorder Traversal.\nMemory Usage: | PratikSen07 | NORMAL | 2022-08-18T08:51:35.908179+00:00 | 2022-08-18T08:54:51.016403+00:00 | 1,855 | false | # **Java Solution (Iterative Approach Using Stack):**\nRuntime: 1 ms, faster than 93.68% of Java online submissions for Binary Tree Preorder Traversal.\nMemory Usage: 41.3 MB, less than 84.60% of Java online submissions for Binary Tree Preorder Traversal.\n```\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n // Create an array list to store the solution result...\n List<Integer> sol = new ArrayList<>();\n // Return the solution answer if the tree is empty...\n if(root == null) return sol;\n // Create an empty stack and push the root node...\n Stack<TreeNode> bag = new Stack<>();\n bag.push(root);\n // Loop till stack is empty...\n while(!bag.isEmpty()){\n // Pop a node from the stack...\n TreeNode node = bag.pop();\n sol.add(node.val);\n // Push the right child of the popped node into the stack...\n if(node.right != null) bag.push(node.right);\n // Push the left child of the popped node into the stack...\n if(node.left != null) bag.push(node.left);\n }\n return sol; // Return the solution list...\n }\n}\n```\n\n# **C++ Solution (Recursive Approach):**\nRuntime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Preorder Traversal.\nMemory Usage: 8.5 MB, less than 42.50% of C++ online submissions for Binary Tree Preorder Traversal.\n```\nclass Solution {\npublic:\n vector<int> sol;\n void preorder(TreeNode* node){\n if(!node) return;\n sol.push_back(node->val);\n preorder(node->left);\n preorder(node->right);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n preorder(root);\n return sol;\n }\n};\n```\n\n# **Python/Python3 Solution (Iterative Approach Using Stack):**\n```\nclass Solution(object):\n def preorderTraversal(self, root):\n # Create an empty stack and push the root node...\n bag = [root]\n # Create an array list to store the solution result...\n sol = []\n # Loop till stack is empty...\n while bag:\n # Pop a node from the stack...\n node = bag.pop()\n if node:\n sol.append(node.val)\n # Append the right child of the popped node into the stack\n bag.append(node.right)\n # Push the left child of the popped node into the stack\n bag.append(node.left)\n return sol # Return the solution list...\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 17 | 0 | ['Stack', 'Recursion', 'C', 'Python', 'Java', 'Python3'] | 0 |
binary-tree-preorder-traversal | Java || 2 Easy Approach with Explanation || DSF and Stack | java-2-easy-approach-with-explanation-ds-m7yo | \n1)\n//Recursive Solution //DFS\nclass Solution \n{\n List<Integer> res= new ArrayList<>();//global ArrayList \n\n public List<Integer> preorderTraversal | swapnilGhosh | NORMAL | 2021-07-07T06:32:47.086605+00:00 | 2021-07-07T06:32:47.086645+00:00 | 903 | false | ```\n1)\n//Recursive Solution //DFS\nclass Solution \n{\n List<Integer> res= new ArrayList<>();//global ArrayList \n\n public List<Integer> preorderTraversal(TreeNode root)\n {\n if(root==null)//base case for the null graph \n return res;\n\n preorder(root);//calling the preorder in order \n\n return res;//returning gthe resultant array list \n }\n\n public void preorder(TreeNode root)\n {\n if(root==null)//base case when we reach to the null node while recuring down hill, returning to the calling function and deleting the activation record \n return;//returning to the call function or the active acttib=vation record \n \n res.add(root.val);//adding first the value, as we first see the root we are adding it to the ArrayList (Root Left Right)\n \n preorder(root.left);//recursing down hill in search of left node \n preorder(root.right);//after the left node is done fo the particular activation record , we are going downhill for the right node search \n \n return;//returning to the calling function or the active activation record and deleting this activation record as all the fuction are completed \n }\n}//Please do Upvote, It helps a lot\n```\n```\n2)\n//Non-Recursive Solution \nclass Solution \n{\n public List<Integer> preorderTraversal(TreeNode root) \n {\n List<Integer> list=new ArrayList<>();//for storing the element inorder \n \n if(root == null)//base case when the tree is empty\n return list;\n \n Stack<TreeNode> stack= new Stack<>();\n \n stack.push(root);//pushing the root node \n \n while(!stack.isEmpty())//terminating condition \n {\n TreeNode temp=stack.pop();//popping the top element \n \n list.add(temp.val);//adding the value to the ArrayList //Root\n \n if(temp.right != null)//first pushing the right because to access the left first and then the right //Right\n stack.push(temp.right);//pushing the right node \n \n if(temp.left != null)//pushing the left node if present after right because to access the left first //Left\n stack.push(temp.left);\n }//the main purpose of pushing this way is to achive Root Left Right pattern of Inorder Traversal \n return list;//returning the List of integer that are stored in Inorder fashion \n }\n}//Please do Upvote, It helps a lot\n``` | 17 | 0 | ['Stack', 'Recursion', 'Binary Tree', 'Iterator', 'Java'] | 1 |
binary-tree-preorder-traversal | Python solution | python-solution-by-zitaowang-cla6 | Recursive:\n\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """ | zitaowang | NORMAL | 2018-08-28T07:06:10.499406+00:00 | 2018-09-17T15:28:34.526380+00:00 | 2,172 | false | Recursive:\n```\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n if not root:\n return []\n elif not root.left and not root.right:\n return [root.val]\n l = self.preorderTraversal(root.left)\n r = self.preorderTraversal(root.right)\n return [root.val]+l+r\n```\nIterative:\n```\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n if not root:\n return []\n res = []\n stack = [root]\n while stack:\n u = stack.pop()\n res.append(u.val)\n if u.right:\n stack.append(u.right)\n if u.left:\n stack.append(u.left)\n return res\n```\nAnother iterative solution:\n```\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n trav = root\n stack = []\n res = []\n while trav or stack:\n if trav:\n stack.append(trav)\n res.append(trav.val)\n trav = trav.left\n else:\n u = stack.pop()\n trav = u.right\n return res\n``` | 17 | 0 | [] | 1 |
binary-tree-preorder-traversal | Share my solution in C | share-my-solution-in-c-by-milu-lms9 | //// iterative solution\n\n int preorderTraversal(struct TreeNode root, int returnSize) {\n int result = NULL;\n if (root == NULL)\n return resu | milu | NORMAL | 2015-10-22T03:35:06+00:00 | 2015-10-22T03:35:06+00:00 | 2,260 | false | //// iterative solution\n\n int* preorderTraversal(struct TreeNode* root, int* returnSize) {\n int *result = NULL;\n if (root == NULL)\n return result;\n \n *returnSize = 0;\n \n struct TreeNode **stack = (struct TreeNode **)malloc(sizeof(struct TreeNode *));\n struct TreeNode *pop;\n int length = 0;\n stack[length++] = root;\n \n while (length > 0) {\n result = (int *)realloc(result, (*returnSize+1)*sizeof(int));\n pop = stack[--length];\n result[*returnSize] = pop->val;\n *returnSize += 1;\n if (pop->right) {\n stack = (struct TreeNode **)realloc(stack, sizeof(struct TreeNode*)*(length+1));\n stack[length++] = pop->right;\n }\n if (pop->left) {\n stack = (struct TreeNode **)realloc(stack, sizeof(struct TreeNode*)*(length+1));\n stack[length++] = pop->left;\n }\n }\n free(stack);\n return result;\n}\n\n//// recursive solution\n\n int* preorderTraversal(struct TreeNode* root, int* returnSize) {\n int *result = NULL;\n if (root == NULL)\n return result;\n result = (int *)malloc(sizeof(int));\n *result = root->val;\n \n int leftsize=0, rightsize=0, *leftarr, *rightarr;\n if (root->left)\n leftarr = preorderTraversal(root->left, &leftsize);\n if (root->right)\n rightarr = preorderTraversal(root->right, &rightsize);\n \n *returnSize = 1 + leftsize + rightsize;\n if (leftsize >0 || rightsize > 0)\n result = (int *)realloc(result, sizeof(int)*(*returnSize));\n \n int i, j;\n for (i=0; i<leftsize; i++)\n result[i+1] = leftarr[i];\n if (leftsize > 0)\n free(leftarr);\n for (j=0; j<rightsize; j++)\n result[i+j+1] = rightarr[j];\n if (rightsize > 0)\n free(rightarr);\n \n return result;\n} | 17 | 0 | [] | 2 |
binary-tree-preorder-traversal | Proper Tree Traversal || DFS || Python Easy || Begineer Friendly || | proper-tree-traversal-dfs-python-easy-be-p9co | Intuition\n Describe your first thoughts on how to solve this problem. \n- The intuition here is to perform a preorder traversal of a binary tree and collect th | Pratikk_Rathod | NORMAL | 2023-09-28T07:48:04.439450+00:00 | 2023-09-28T07:48:04.439499+00:00 | 1,606 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The intuition here is to perform a preorder traversal of a binary tree and collect the values of the nodes in a list as you traverse the tree.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We can implement a recursive approach to perform a preorder traversal of the tree.\n- Initialize an empty list `arr` to store the values of the nodes in the preorder traversal.\n- Start the traversal from the root node. If the node is not None, append its value to `arr`, and then recursively traverse its left and right subtrees.\n- Return the `arr` list containing the preorder traversal values.\n\n# Complexity\n- Time complexity:\n - The time complexity of this approach is $$O(n)$$, where n is the number of nodes in the binary tree. This is because we visit each node exactly once during the traversal.\n- Space complexity:\n - The space complexity is also $$O(n)$$ due to the space used by the `arr` list to store the traversal values. In the worst case, the list will contain all the nodes\' values.\n\n# Code\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def __init__(self):\n self.arr = []\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is not None:\n self.arr.append(root.val)\n self.preorderTraversal(root.left)\n self.preorderTraversal(root.right)\n return self.arr\n``` | 16 | 0 | ['Stack', 'Tree', 'Depth-First Search', 'Binary Tree', 'Python', 'Python3'] | 0 |
binary-tree-preorder-traversal | Python Preorder/Inorder/Postorder Iterative and Recursive Summary | python-preorderinorderpostorder-iterativ-l3nn | Preorder:\n144. Binary Tree Preorder Traversal\n> Time Complexity O(N)\n> Space Complexity O(1)\n\n## Recursively\ndef preorderTraversal1(self, root):\n res | letscoding_john | NORMAL | 2019-09-06T16:06:22.421179+00:00 | 2019-09-06T16:10:11.670119+00:00 | 2,602 | false | Preorder:\n**144. Binary Tree Preorder Traversal**\n> Time Complexity O(N)\n> Space Complexity O(1)\n```\n## Recursively\ndef preorderTraversal1(self, root):\n res = []\n self.dfs(root, res)\n return res\n \ndef dfs(self, root, res):\n if root:\n res.append(root.val)\n self.dfs(root.left, res)\n self.dfs(root.right, res)\n\t\t\n## Iteratively\ndef preorderTraversal(self, root):\n def preorderTraversal(self, root):\n stack, res = [], []\n while stack or root:\n if root:\n stack.append(root)\n res.append(root.val) \n root = root.left \n else:\n node = stack.pop()\n root = node.right\n return res\n```\nInorder\n**94. Binary Tree Inorder Traversal**\n> Time Complexity O(N)\n> Space Complexity O(1)\n```\n\n## Recursively\ndef inorderTraversal(self, root):\n\tres = []\n\tself.helper(root, res)\n\treturn res\n\ndef helper(self, root, res):\n\tif root:\n\t\tself.helper(root.left, res)\n\t\tres.append(root.val)\n\t\tself.helper(root.right, res)\n\n## Iteratively\ndef inorderTraversal(self, root):\n res = []\n stack = []\n while stack or root:\n if root:\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n res.append(node.val)\n root = node.right \n return res\n```\nPreorder\n**145. Binary Tree Postorder Traversal**\n> Time Complexity O(N)\n> Space Complexity O(1)\n```\n## Recursively\ndef postorderTraversal(self, root):\n\tself.res = []\n\tself.dfs(root)\n\treturn self.res\n\ndef dfs(self, root):\n\tif not root:\n\t\treturn \n\tself.dfs(root.left)\n\tself.dfs(root.right) \n\tself.res.append(root.val)\n\t\n## Iteratively\ndef postorderTraversal(self, root):\n\tstack, res = [], []\n\twhile stack or root:\n\t\tif root:\n\t\t\tstack.append(root)\n\t\t\tres.append(root.val) \n\t\t\troot = root.right \n\t\telse:\n\t\t\tnode = stack.pop()\n\t\t\troot = node.left\n\treturn res[::-1]\n``` | 16 | 3 | ['Tree'] | 0 |
binary-tree-preorder-traversal | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-dnrx | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right | sergeyleschev | NORMAL | 2022-04-13T05:46:47.115640+00:00 | 2022-04-13T05:46:47.115688+00:00 | 476 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\nclass Solution {\n func preorderTraversal(_ root: TreeNode?) -> [Int] {\n var res: [Int] = []\n \n func preOrder(_ root: TreeNode?) {\n guard let root = root else { return }\n \n res.append(root.val)\n preOrder(root.left)\n preOrder(root.right)\n }\n \n preOrder(root)\n return res\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 15 | 0 | ['Swift'] | 2 |
binary-tree-preorder-traversal | [C++] 100% Time - DFS Recursive vs. Iterative Solutions Explained and Compared | c-100-time-dfs-recursive-vs-iterative-so-vstq | First in the easy, convenient way of a plain DFS: we just move left as much as possible, update res at each step and only then we have met the last left branch | ajna | NORMAL | 2020-07-24T18:48:50.521394+00:00 | 2020-07-24T18:48:50.521423+00:00 | 1,122 | false | First in the easy, convenient way of a plain DFS: we just move `left` as much as possible, update `res` at each step and only then we have met the last `left` branch on our current path we start considering going to the `right`:\n\n```cpp\nclass Solution {\npublic:\n vector<int> res;\n void dfs(TreeNode *root) {\n if (!root) return;\n res.push_back(root->val);\n dfs(root->left);\n dfs(root->right);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n dfs(root);\n return res;\n }\n};\n```\n\nThe iterative solution does not take too much effort either, it is just potentially less intuitive; let\'s go with a DFS for this one as well, since going for a BFS would require needless extra complexity and more logic as we go (in other words: the interviewer should really hate you for that); the structure will be similar: class accumulator variable `res`, no external helper function needed for this one and nice loop inside to build the result.\n\nWe start checking if the tree is empty, in which case we just return our `res`, empty as well. If not, we declare a stack `s` and initialise it with a first push, `root` itself.\n\nNow the fun begins: we loop while our stack is not empty, we pop the last element, we add back its possible child - but not that we add `right` first, `left` second, since in a stack the values come out following a LIFO approach.\n\nTry to visualise it with the example tree of any other one you might wish to build; use pen and paper if not sure, but it works :)\n\nOnce the stack is empty, we are done: time to return `res`.\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n vector<int> res;\n vector<int> preorderTraversal(TreeNode* root) {\n if (!root) return res;\n stack<TreeNode*> s;\n s.push(root);\n TreeNode *currNode;\n while (s.size()) {\n currNode = s.top();\n s.pop();\n res.push_back(currNode->val);\n if (currNode->right) s.push(currNode->right);\n if (currNode->left) s.push(currNode->left);\n }\n return res;\n }\n};\n``` | 15 | 0 | ['Depth-First Search', 'Recursion', 'C', 'Iterator', 'C++'] | 3 |
binary-tree-preorder-traversal | Easiest Traversal Without Stack & Queue || 100% || Preorder. | easiest-traversal-without-stack-queue-10-mxp0 | Using This Solution We Can Make Preorder Traversal In Binary Tree Without Using Stack And Queue.\n\n##### Global Declaration Of Ans Vector.\n\nclass Solution {\ | Bluster980 | NORMAL | 2022-08-06T06:37:02.343859+00:00 | 2023-07-01T18:49:37.264320+00:00 | 135 | false | ## **Using This Solution We Can Make Preorder Traversal In Binary Tree Without Using Stack And Queue.**\n\n##### Global Declaration Of Ans Vector.\n```\nclass Solution {\npublic:\n vector<int> v;\n vector<int> preorderTraversal(TreeNode* root) {\n if(root == NULL){\n return v;\n }\n v.push_back(root->val);\n preorderTraversal(root->left);\n preorderTraversal(root->right);\n return v;\n }\n};\n```\n\n##### Pass By Reference Ans Vector.\n\n```\nclass Solution {\npublic:\n void helper(TreeNode *root, vector<int> &ans){\n if(root == NULL) return;\n ans.push_back(root->val);\n helper(root->left,ans);\n helper(root->right,ans);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans; helper(root,ans);\n return ans;\n }\n};\n```\n\n**Like & UpVote If You Get My Intuition Also Comment If You Have Any Query..**\n\n | 14 | 0 | ['Tree', 'Binary Search Tree'] | 2 |
binary-tree-preorder-traversal | Python | Recursive & Iterative | Simple Solutions | python-recursive-iterative-simple-soluti-172t | Recursive Solution\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val | akash3anup | NORMAL | 2021-10-10T18:47:27.880502+00:00 | 2021-10-10T18:47:27.880534+00:00 | 1,134 | false | ### Recursive Solution\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traversal(self, root, preorder):\n if root:\n preorder.append(root.val)\n self.traversal(root.left, preorder)\n self.traversal(root.right, preorder)\n \n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n preorder = []\n self.traversal(root, preorder)\n return preorder\n```\n\n### Iterative Solution\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n preorder = []\n stack = [root]\n while stack:\n root = stack.pop()\n if root:\n preorder.append(root.val)\n stack.append(root.right)\n stack.append(root.left)\n return preorder\n```\n\n***If you liked the above solution then please upvote!*** | 14 | 0 | ['Python'] | 0 |
binary-tree-preorder-traversal | 🔥 [LeetCode The Hard Way]🔥 DFS | Pre Order | Explained Line By Line | leetcode-the-hard-way-dfs-pre-order-expl-1pvc | \uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord for live discussion.\n\uD83D\uDF | __wkw__ | NORMAL | 2022-09-08T11:37:01.576131+00:00 | 2023-01-09T02:34:59.930618+00:00 | 1,971 | false | \uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [YouTube Channel](https://www.youtube.com/channel/@leetcodethehardway) if you are interested.\n\n---\n\nYou may also check out my recent DFS solutions on other tree problems.\n\n- [987. Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2527028/leetcode-the-hard-way-easy-dfs-explained-line-by-line)\n- [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511705/leetcode-the-hard-way-dfs-explained-line-by-line)\n- [814. Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/discuss/2537510/leetcode-the-hard-way-easy-dfs-explained-line-by-line)\n- [606. Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/discuss/2542523/leetcode-the-hard-way-dfs-5-cases-explained-line-by-line)\n\nThe steps for pre-order is \n- do something with root value\n- traverse left subtree \n- traverse right sub tree. \n\nFor example 1, starting the root node 1.\n\n - At node 1 now, add root value which is 1. answer = [1]\n- At node 1 now, traverse left node, however, there is no left node, hence return.\n- At node 1 now, traverse right node.\n- At node 2 now, add root value which is 2. answer = [1, 2]\n- At node 2 now, traverse left node.\n- At node 3 now, add root value which is 3. answer = [1, 2, 3]\n- At node 3 now, traverse left node, however, there is no left node, hence return.\n- At node 3 now, traverse right node, however, there is no right node, hence return.\n- At node 2 now, traverse right node, however, there is no right node, hence return.\n\n**C++**\n\n```cpp\n// Time Complexity: O(N)\n// Space Complexity: O(N)\n\n// This is a standard pre-order traversal problem, I\'d suggest to learn in-order and post-order as well.\n// Here\'s a short tutorial if you\'re interested.\n// https://wingkwong.github.io/leetcode-the-hard-way/tutorials/graph-theory/binary-tree\n// then you may try the following problems \n// 94. Binary Tree Inorder Traversal: https://leetcode.com/problems/binary-tree-inorder-traversal/\n// 145. Binary Tree Postorder Traversal: https://leetcode.com/problems/binary-tree-postorder-traversal/\n\nclass Solution {\npublic:\n vector<int> ans;\n void preorder(TreeNode* node) {\n if (node == NULL) return;\n // do something with node value here\n ans.push_back(node->val);\n // traverse the left node\n preorder(node->left);\n // traverse the right node\n preorder(node->right);\n }\n \n vector<int> preorderTraversal(TreeNode* root) {\n preorder(root);\n return ans;\n }\n};\n```\n\n**Python**\n\n```py\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# This is a standard pre-order traversal problem, I\'d suggest to learn in-order and post-order as well.\n# Here\'s a short tutorial if you\'re interested.\n# https://wingkwong.github.io/leetcode-the-hard-way/tutorials/graph-theory/binary-tree\n# then you may try the following problems \n# 94. Binary Tree Inorder Traversal: https://leetcode.com/problems/binary-tree-inorder-traversal/\n# 145. Binary Tree Postorder Traversal: https://leetcode.com/problems/binary-tree-postorder-traversal/\n\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\t# root -> left -> right\n return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) if root else []\n``` | 13 | 1 | ['Recursion', 'C', 'Python', 'C++', 'Python3'] | 0 |
binary-tree-preorder-traversal | [JavaScript] Simple iterative solution | javascript-simple-iterative-solution-by-rkn42 | \nvar preorderTraversal = function(root) {\n const result = [];\n const stack = [];\n let node = root;\n \n while (node) {\n node.val && result.push(nod | pdxandi | NORMAL | 2018-10-25T23:14:00.058047+00:00 | 2018-10-25T23:14:00.058106+00:00 | 1,003 | false | ```\nvar preorderTraversal = function(root) {\n const result = [];\n const stack = [];\n let node = root;\n \n while (node) {\n node.val && result.push(node.val); \n node.right && stack.push(node.right); \n node = node.left || stack.pop(); \n }\n \n return result;\n};\n``` | 13 | 0 | [] | 2 |
binary-tree-preorder-traversal | Easy to read JAVA solutions for both iterative and recursive (<300ms) | easy-to-read-java-solutions-for-both-ite-g5be | Recursive:\n\n public class Solution {\n List traversal = new ArrayList<>();\n public List preorderTraversal(TreeNode root) {\n if(r | 2010zhouyang | NORMAL | 2015-08-03T21:27:56+00:00 | 2015-08-03T21:27:56+00:00 | 1,858 | false | Recursive:\n\n public class Solution {\n List<Integer> traversal = new ArrayList<>();\n public List<Integer> preorderTraversal(TreeNode root) {\n if(root!=null){helper(root);}\n return traversal;\n }\n \n void helper (TreeNode root){\n traversal.add(root.val);\n if(root.left!=null){helper(root.left);}\n if(root.right!=null){helper(root.right);}\n \n }\n }\n\nIterative: Use Stack\n\n public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n Stack<TreeNode> stack = new Stack<>();\n List<Integer> traversal = new ArrayList<>();\n if(root!=null){\n stack.push(root);\n while(!stack.isEmpty()){\n TreeNode curr = stack.pop();\n traversal.add(curr.val);\n if(curr.right!=null){ stack.push(curr.right); }\n if(curr.left!=null){ stack.push(curr.left); }\n }\n }\n return traversal;\n }\n } | 13 | 0 | [] | 1 |
binary-tree-preorder-traversal | Video solution | Template sol. for all traversals (Preorder, Inorder, Postorder) | With Examples | video-solution-template-sol-for-all-trav-hulo | Video\nHey everyone i have created a video solution for all DFS traversals (Preorder, Inorder, Postorder) for binary trees, it has a template solution which wil | _code_concepts_ | NORMAL | 2024-07-09T09:50:06.104755+00:00 | 2024-07-12T10:20:34.013717+00:00 | 1,246 | false | # Video\nHey everyone i have created a video solution for all DFS traversals (Preorder, Inorder, Postorder) for binary trees, it has a template solution which will help you to implement all the travesals in one go, i have also tried to explain each travesal with a practical example, so that you understand why these traversals are important.\nHere is the video link :\nlanguage used is hindi->\n**Recursive**:\nhttps://www.youtube.com/watch?v=9XJdlw3y4sk\n**Iterative**:\nhttps://youtu.be/iZbG5_gvsJI\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n stack<TreeNode*> st;\n vector<int> ans;\n\n while(!st.empty() || root){\n while(root){\n ans.push_back(root->val);\n st.push(root);\n root=root->left;\n }\n root=st.top();\n st.pop();\n root=root->right;\n }\n return ans;\n\n \n \n }\n};\n``` | 12 | 0 | ['C++'] | 1 |
binary-tree-preorder-traversal | Java easy solution 0ms 100% faster || Recursion | java-easy-solution-0ms-100-faster-recurs-cz2s | Code\n\njava\npublic List<Integer> preorderTraversal(TreeNode root) {\n\tList<Integer> list = new ArrayList<>();\n\tpreorder(root, list);\n\treturn list;\n}\n\n | Chaitanya31612 | NORMAL | 2021-11-20T15:29:18.377419+00:00 | 2021-11-20T15:29:18.377447+00:00 | 609 | false | **Code**\n\n```java\npublic List<Integer> preorderTraversal(TreeNode root) {\n\tList<Integer> list = new ArrayList<>();\n\tpreorder(root, list);\n\treturn list;\n}\n\npublic void preorder(TreeNode root, List<Integer> list) {\n\tif(root == null) return;\n\n\tlist.add(root.val);\n\tpreorder(root.left, list);\n\tpreorder(root.right, list);\n}\n```\n\nHope it helps\nDo upvote\nThanks | 12 | 1 | ['Recursion', 'Java'] | 0 |
binary-tree-preorder-traversal | Simple recursive JavaScript solution | simple-recursive-javascript-solution-by-wugcr | \nvar preorderTraversal = function solution(root) {\n if (!root) {\n return [];\n }\n \n return [root.val, ...solution(root.left), ...solutio | nnigmat | NORMAL | 2021-01-08T12:36:21.685940+00:00 | 2021-01-08T12:36:53.369030+00:00 | 703 | false | ```\nvar preorderTraversal = function solution(root) {\n if (!root) {\n return [];\n }\n \n return [root.val, ...solution(root.left), ...solution(root.right)];\n};\n``` | 12 | 0 | ['Recursion', 'JavaScript'] | 1 |
binary-tree-preorder-traversal | Iterative and Recursive DFS JS Solutions | iterative-and-recursive-dfs-js-solutions-bnf6 | \n// Iterative DFS Solution\nvar preorderTraversal = function(root) {\n if (!root) return [];\n let stack = [], res = [];\n stack.push(root);\n whil | hbjorbj | NORMAL | 2020-10-05T20:11:58.889330+00:00 | 2021-06-25T15:10:21.700915+00:00 | 1,289 | false | ```\n// Iterative DFS Solution\nvar preorderTraversal = function(root) {\n if (!root) return [];\n let stack = [], res = [];\n stack.push(root);\n while (stack.length) {\n let node = stack.pop();\n res.push(node.val);\n if (node.right) stack.push(node.right);\n if (node.left) stack.push(node.left);\n }\n return res;\n\t// Time Complexity: O(n)\n // Space Complexity: O(n)\n};\n```\n\n```\n// Recursive DFS Solution\nvar preorderTraversal = function(root, res = []) {\n if (!root) return [];\n res.push(root.val);\n if (root.left) preorderTraversal(root.left, res);\n if (root.right) preorderTraversal(root.right, res);\n return res;\n // Time Complexity: O(n)\n // Space Complexity: O(n)\n}\n``` | 12 | 0 | ['JavaScript'] | 5 |
binary-tree-preorder-traversal | Easy , Beginner friendly & Dry run ||Pre Order Traversal || Time O(n) & Space O(n) || Gits✅✅😎😎 | easy-beginner-friendly-dry-run-pre-order-kqiv | Guys if the solution and explanation is helpful the upvote me.\u2764\uFE0F\u2764\uFE0F\n\n\n\n# Approach \uD83D\uDC48\n\n- In the question given, the root of a | GiteshSK_12 | NORMAL | 2024-02-05T07:20:14.917769+00:00 | 2024-02-05T07:20:14.917800+00:00 | 999 | false | # Guys if the solution and explanation is helpful the upvote me.\u2764\uFE0F\u2764\uFE0F\n\n\n\n# Approach \uD83D\uDC48\n\n- In the question given, the root of a binary tree is provided, and the goal is to return a list of the nodes\' values in pre-order traversal. We will use recursion to solve this problem.\n\n- To accomplish a pre-order traversal, we need to understand its process, which involves recursively going through all nodes of the tree by first visiting the root node, then the left subtree, and finally the right subtree.\n\n# What is Pre-Order traversal - \uD83D\uDC48\n\n- In preorder traversal, first, root node is visited, then left sub-tree and after that right sub-tree is visited. The process of preorder traversal can be represented as -\n `root \u2192 left \u2192 right` \n\n- Root node is always traversed first in preorder traversal, while it is the last item of postorder traversal. Preorder traversal is used to get the prefix expression of a tree.\n\n# How does Pre-Order Traversal of Binary Tree Work? \uD83D\uDC48\n\nConsider the following tree:\n\n\n\n**Step 1:** \n- At first the root will be visited, i.e. node 1.\n\n\n\n**Step 2:** \n- After this, traverse in the left subtree. Now the root of the left subtree is visited i.e., node 2 is visited.\n\n\n\n**Step 3:** \n- Again the left subtree of node 2 is traversed and the root of that subtree i.e., node 4 is visited.\n\n\n\n**Step 4:** \n- There is no subtree of 4 and the left subtree of node 2 is visited. So now the right subtree of node 2 will be traversed and the root of that subtree i.e., node 5 will be visited.\n\n\n\n**Step 5:** \n- The left subtree of node 1 is visited. So now the right subtree of node 1 will be traversed and the root node i.e., node 3 is visited.\n\n\n\n**Step 6:**\n- Node 3 has no left subtree. So the right subtree will be traversed and the root of the subtree i.e., node 6 will be visited. After that there is no node that is not yet traversed. So the traversal ends.\n\n\n\nSo the order of traversal of nodes is 1 -> 2 -> 4 -> 5 -> 3 -> 6.\n\n# Code Explanation: \uD83D\uDC48\n\n**The helper Method:** \n- This method is designed to perform the recursive pre-order traversal. It accepts a TreeNode (representing the current node being visited) and an ArrayList<Integer> (to collect the values of the nodes in pre-order).\n \n- The method works as follows:\n\n - **Base Case:** If the current node (root) is null, it returns immediately, as there is nothing to process. This condition is crucial for ending the recursion, especially when dealing with leaf nodes\' children, which are null.\n\n - **Process the Current Node:** If the current node is not null, its value is added to the ans list. This step corresponds to the "Root" part of the pre-order traversal.\n\n - **Recursive Calls:** The method then makes recursive calls first to the left child (helper(root.left, ans)) and then to the right child (helper(root.right, ans)). These calls ensure that all nodes in the left subtree are visited before moving to the right subtree, adhering to the pre-order traversal order.\n\n**The preorderTraversal Method:** \n- This is the public method that initiates the traversal. It does the following:\n\n - **Initialize the ArrayList:** An ArrayList<Integer> named ans is created to store the values of the nodes visited during the traversal.\n\n - **Check for Empty Tree:** If the input root is null, indicating an empty tree, the method returns the empty ans list immediately.\n\n - **Start Recursive Traversal:** If the tree is not empty, it calls the helper method with the root of the tree and the ans list. After this method call completes, ans will contain the values of all the nodes in pre-order.\n\n - **Return the List:** Finally, the method returns the ans list, which now holds the result of the pre-order traversal.\n\n# Complexity \uD83D\uDC48\nTime complexity: O(n)\n\nSpace complexity: O(log n) to O(n)\n\n# Code \uD83D\uDC48\n```C++ []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n void helper(TreeNode* root ,vector<int>& arr){\n if(root == NULL)return ;\n arr.push_back(root->val);\n helper(root->left , arr);\n helper(root->right , arr);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int>arr;\n if(root == NULL)return arr;\n helper(root , arr);\n return arr;\n }\n};\n```\n```Java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public void helper(TreeNode root , ArrayList<Integer> ans){\n if(root == null)return;\n ans.add(root.val);\n helper(root.left , ans);\n helper(root.right , ans);\n }\n public List<Integer> preorderTraversal(TreeNode root) {\n ArrayList<Integer> ans = new ArrayList<>();\n if(root == null)return ans;\n helper(root , ans);\n return ans;\n }\n}\n```\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nfunction helper(root, ans) {\n if (root === null) return;\n ans.push(root.val); \n helper(root.left, ans); \n helper(root.right, ans); \n}\nvar preorderTraversal = function(root) {\n const ans = []\n if(root === null)return ans\n helper(root , ans)\n return ans\n};\n```\n```C# []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public int val;\n * public TreeNode left;\n * public TreeNode right;\n * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\npublic class Solution {\n public void helper(TreeNode root , IList<int> ans){\n if(root == null)return;\n ans.Add(root.val);\n helper(root.left , ans);\n helper(root.right , ans);\n }\n public IList<int> PreorderTraversal(TreeNode root) {\n List<int> ans = new List<int>();\n if(root == null)return ans;\n helper(root , ans);\n return ans;\n }\n}\n```\n```python []\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def helper(self , root , ans):\n if root == None: return\n ans.append(root.val)\n self.helper(root.left , ans)\n self.helper(root.right , ans)\n\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n ans = []\n if root == None : return ans\n self.helper(root , ans)\n return ans\n \n```\n```python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def helper(self , root , ans):\n if root == None: return\n ans.append(root.val)\n self.helper(root.left , ans)\n self.helper(root.right , ans)\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n if root == None : return ans\n self.helper(root , ans)\n return ans\n```\n```ruby []\n# Definition for a binary tree node.\n# class TreeNode\n# attr_accessor :val, :left, :right\n# def initialize(val = 0, left = nil, right = nil)\n# @val = val\n# @left = left\n# @right = right\n# end\n# end\n# @param {TreeNode} root\n# @return {Integer[]}\ndef helper(root , ans)\n if root == nil\n return\n end\n ans.append(root.val)\n helper(root.left , ans)\n helper(root.right , ans)\nend\ndef preorder_traversal(root)\n ans = []\n if root == nil \n return ans\n end\n helper(root , ans)\n return ans\nend\n```\n# Dry Run \uD83D\uDE0E\n\n**1. Initialization:**\n- The preorderTraversal method is called with the root node of the binary tree.\n- Since the root is not null, an ArrayList<Integer> named ans is created to store the traversal result.\n- `ArrayList<Integer> ans = new ArrayList<>();`\n\n**2. First helper Call with Root Node (1):**\n\n- The helper method is called with the root node (which has the value 1) and the ans list.\n- Since root is not null, root.val (which is 1) is added to ans. Now, ans = [1]. `ans.add(root.val);`\n- The method then recursively calls itself for `root.left`, which is null, and immediately returns due to the base case.\n- Next, it calls itself for `root.right`, which is the node with the value 2.\n\n**3. Recursive helper Call with Node (2):**\n\n- For the node with the value 2, since it\'s not null, 2 is added to ans. Now, ans = [1, 2].\n- The method then recursively calls itself for `root.left` of node 2, which is the node with the value 3.\n\n**4. Recursive helper Call with Node (3):**\n\n- For the node with the value 3, since it\'s not null, 3 is added to ans. Now, ans = [1, 2, 3].\n- The method then attempts to call itself for both `root.left` and `root.right` of node 3, both of which are null. Both recursive calls immediately return due to the base case.\n\n**5. Backtracking and Completion:**\n\n- After processing node 3, the recursion unwinds back to node 2, and since both its left and right children (only left in this case) have been processed, it returns to the first call (node 1).\n- With both the right subtree of node 1 processed (there\'s no left subtree), the initial call to helper completes.\n\n**6. Return Result:**\n\n- The preorderTraversal method now returns the ans list, which contains the pre-order traversal result: [1, 2, 3].\n\n# Guys if the solution and explanation is helpful the upvote me.\n\n\n\n\n\n\n\n\n\n\n\n | 10 | 0 | ['Array', 'Tree', 'Binary Tree', 'Python', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript', 'C#'] | 2 |
binary-tree-preorder-traversal | C++ || Recursion || Full Explanation | c-recursion-full-explanation-by-nirdeshd-ub5g | Intuition\n Describe your first thoughts on how to solve this problem. \n- Using Recursive Approach.\n\n# Approach\n- A binary tree is a recursive object where | nirdeshdevadiya17 | NORMAL | 2023-01-09T02:43:18.876217+00:00 | 2023-01-09T02:43:18.876257+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Using Recursive Approach.\n\n# Approach\n- A binary tree is a recursive object where we have three essential components\n - Root node: The topmost node of a binary tree.\n\n - Left-subtree: A smaller binary tree connected via the left pointer of root node.\n\n - Right-subtree: A smaller binary tree connected via the right pointer of root node.\n\n- So traversing a binary tree requires traversal of each component Processing root node, traversing the left subtreeand traversing the right subtree.\n\n\n\n## Recursive preorder traversal of binary tree \n- In recursive preorder traversal, we first process the root node, then process all nodes in the left subtree, and finally, we process all nodes in the right subtree Suppose we use a function precrder(root) with root as an input parameter.\n\n### Steps of recursive preorder implementation\n\n- First, store data stored in the root node i.e process(root->value) in vector\n- Then we recursively traverse and process each node in the left subtree by calling the same function with root->left as input parameter i.e preorder(root->left).\n- Then we recursively traverse and process each node in the right subtree by calling the same function with rout->right as input parameter ie preorder(root->right). \n- Base case: recursion will terminate and backtrack when it reaches the bottommost end of binary tree, i.e root==NULL\n\n\n\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n void preorder(TreeNode* root, vector<int> &a)\n {\n // Base Case\n if(root==NULL)\n return;\n\n a.push_back(root->val);// store in vector\n preorder(root->left,a);// recursion for left sub tree\n preorder(root->right,a);// recursion for right sub tree\n }\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> a;\n preorder(root,a);\n return a;\n }\n};\n``` | 10 | 0 | ['Tree', 'Recursion', 'C++'] | 0 |
binary-tree-preorder-traversal | Three ways of Iterative Preorder Traversing. Easy Explanation | three-ways-of-iterative-preorder-travers-l2ip | Three types of Iterative Preorder Traversals in java. \n\n1) Using 1 Stack. O(n) Time & O(n) Space\n\t Print and push all left nodes into the stack till it hits | xruzty | NORMAL | 2016-10-24T18:35:22.076000+00:00 | 2016-10-24T18:35:22.076000+00:00 | 2,233 | false | Three types of Iterative Preorder Traversals in java. \n\n1) **Using 1 Stack.** O(n) Time & O(n) Space\n\t* Print and push all `left` nodes into the `stack` till it hits `NULL`.\n\t* Then `Pop` the top element from the stack, and make the `root` point to its `right`.\n\t* Keep iterating till `both` the below conditions are met -\n\t\t* Stack is empty `and`\n * Root is NULL.\n\t\n\n```\n\npublic List<Integer> preorderTraversal(TreeNode root) {\n\t\tList<Integer> out = new ArrayList<Integer>();\n\t\tif(root==null)\n\t\t\treturn out;\n\t\tStack<TreeNode> s = new Stack(); \n\t\twhile(root!=null || !s.empty()){\n\t\t\tif(root!=null){\n\t\t\t\tout.add(root.val);\n\t\t\t\ts.push(root);\n\t\t\t\troot = root.left;\n\t\t\t}\n\t\t\telse{\n\t\t\t\troot = s.pop();\t\t\t\t\n\t\t\t\troot = root.right;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\t\n```\n\n2) **Using 2 Stacks.** O(n) Time & O(n) Space\nWe use two stacks. Stack `s` is used to find and traverse the child nodes, and `path` stack keeps track of the path from the `root` to the current node. (This is usefull in certain problems like [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) and [Path Sum](https://leetcode.com/problems/path-sum/) ). \n * Initially we push the `root` into `s`.\n\t* Keep iterating with below logic till `s` is `empty`.\n\t\t* `root` = `s.peek()`\n\t\t* If the top elements of both the stacks are not the same :\t\t\n\t\t\t* Print `root` and push it into `path`.\n\t\t\t* Push `root`\'s children into `s` in reverse order. (Remember it\'s a stack!)\n\t\t* When top elements of both stacks are equal. (Which means we hit a deadend, and need to turn back)\n\t\t\t* `Pop` from `both` stacks.\n\t\n\t\n```\n\npublic List<Integer> preorderTraversal(TreeNode root) {\n\t\tList<Integer> out = new ArrayList<Integer>();\n if(root == null)\n return out; \n Stack<TreeNode> s = new Stack(), path = new Stack();\n s.push(root);\n while(!s.empty()){\n root = s.peek();\n if(!path.empty() && path.peek()==root){\n s.pop();\n path.pop();\n }\n else{\n out.add(root.val);\n path.push(root);\n if(root.right != null)\n s.push(root.right);\n if(root.left != null)\n s.push(root.left);\n }\n }\n\t return out;\n }\n\t\n```\n\n3) **Using No Stacks (Morris Traversal).** O(n) Time & O(1) Space\nInstead of using stacks to remember our way back up the tree, we are going to modify the tree to create upwards links. The idea is based on [Threaded Binary Tree](https://en.wikipedia.org/wiki/Threaded_binary_tree). \n\t* Iterate till `root` is null.\n\t\t* If `root` has a left child.\n\t\t\t* Find the `inorder predecessor`. (Inorder predecessor of root is the right most child of its left child)\n\t\t\t\t* Make it point to root.\n\t\t\t\t* `root` = `root.left`.\n\t\t\t* If its already pointing to root (which means we have traversed it already and are on our way up.)\n\t\t\t\t* Make the `inorder predecessor` point to `null` (Reverting our structural changes)\n\t\t\t\t* `root` = `root.right`.\n\t\t* If left child is `null`\n\t\t\t* `root` = `root.right`. (We are climbing up our link.)\n\n\t\t\t\n```\n\npublic List<Integer> preorderTraversal(TreeNode root) {\n\t\tList<Integer> out = new ArrayList<Integer>();\n\t\tif(root == null)\n\t\t\treturn out;\n\t\tTreeNode pre = null;\n\t\twhile(root!=null){\n\t\t\tif(root.left !=null){\n\t\t\t\tpre = root.left;\n\t\t\t\t\twhile(pre.right!=null && pre.right!=root)\n\t\t\t\t\tpre=pre.right;\n\t\t\t\tif(pre.right==null){\n\t\t\t\t\tout.add(root.val);\n\t\t\t\t\tpre.right=root;\n\t\t\t\t\troot=root.left;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tpre.right=null;\n\t\t\t\t\troot=root.right;\n\t\t\t\t} \n\t\t\t}\n\t\t\telse{\n\t\t\t\tout.add(root.val);\n\t\t\t\troot=root.right;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\t\n```\n\nAlso checkout [Inorder](https://discuss.leetcode.com/topic/64682/three-ways-of-iterative-inorder-traversing-easy-explanation) & [PostOrder](https://discuss.leetcode.com/topic/64689/three-ways-of-iterative-postorder-traversing-easy-explanation) :)) | 10 | 0 | [] | 1 |
binary-tree-preorder-traversal | Morris Traversal In Order, pre Order, Post Order | morris-traversal-in-order-pre-order-post-seo5 | \n# Code\njava []\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> preorder = new ArrayList<>();\n | Dixon_N | NORMAL | 2024-09-04T20:42:57.863078+00:00 | 2024-09-04T20:42:57.863111+00:00 | 792 | false | \n# Code\n```java []\npublic class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> preorder = new ArrayList<>();\n TreeNode cur = root;\n \n while (cur != null) {\n if (cur.left == null) {\n preorder.add(cur.val);\n cur = cur.right;\n } else {\n TreeNode prev = cur.left;\n while (prev.right != null && prev.right != cur) {\n prev = prev.right;\n }\n \n if (prev.right == null) {\n prev.right = cur;\n preorder.add(cur.val); \n cur = cur.left;\n } else {\n prev.right = null;\n cur = cur.right;\n }\n }\n }\n \n return preorder;\n }\n}\n\n```\n```java []\npublic class Solution {\n public List<Integer> inorderTraversal(TreeNode root) {\n List<Integer> inorder = new ArrayList<>();\n TreeNode cur = root;\n\n while (cur != null) {\n if (cur.left == null) {\n inorder.add(cur.val);\n cur = cur.right;\n } else {\n TreeNode prev = cur.left;\n while (prev.right != null && prev.right != cur) {\n prev = prev.right;\n }\n\n if (prev.right == null) {\n prev.right = cur;\n cur = cur.left;\n } else {\n prev.right = null;\n inorder.add(cur.val);\n cur = cur.right;\n }\n }\n }\n return inorder;\n }\n}\n```\n```java []\npublic class Solution {\n public List<Integer> postorderTraversal(TreeNode root) {\n List<Integer> postorder = new ArrayList<>();\n TreeNode cur = root;\n \n while (cur != null) {\n if (cur.right == null) {\n postorder.add(cur.val);\n cur = cur.left;\n } else {\n TreeNode pred = cur.right;\n while (pred.left != null && pred.left != cur) {\n pred = pred.left;\n }\n \n if (pred.left == null) {\n pred.left = cur;\n postorder.add(cur.val);\n cur = cur.right;\n } else {\n pred.left = null;\n cur = cur.left;\n }\n }\n }\n \n Collections.reverse(postorder);\n return postorder;\n }\n}\n\n```\n | 9 | 0 | ['Tree', 'Java'] | 5 |
binary-tree-preorder-traversal | Python 3 (30ms) | Perfect Pythonic Recursive One-Liner | Easy to Understand | python-3-30ms-perfect-pythonic-recursive-useb | \nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return [roo | MrShobhit | NORMAL | 2022-01-27T15:08:16.960883+00:00 | 2022-01-27T15:08:16.960916+00:00 | 1,225 | false | ```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)\n\n``` | 9 | 0 | ['Recursion', 'Binary Tree', 'Python', 'Python3'] | 2 |
binary-tree-preorder-traversal | C# Recursive and Iterative (using Stack) with explanation | c-recursive-and-iterative-using-stack-wi-s2je | Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree. \n> Preorder: visit > left > right\n\nItera | minaohhh | NORMAL | 2021-06-09T08:05:29.551305+00:00 | 2021-06-09T08:08:29.994478+00:00 | 1,260 | false | Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree. \n> Preorder: **visit > left > right**\n\n**Iterative Approach**\n* We need to use a `Stack` to remember the sub-trees as we go deeper\n* Since `stack`s are `first-in-last-out` approach, we need to:\n\t* **Visit**: Add the node to the `list`\n\t* `Push` the `right sub-tree` first, then\n\t* `Push` the `left sub-tree`\n* So, when we `pop` the stack, \n\t* We get the `left sub-tree` first *before* the `right sub-tree` since it\'s pushed last\n\n```csharp\npublic class Solution {\n public IList<int> PreorderTraversal(TreeNode root) {\n IList<int> preorder = new List<int>();\n \n Stack<TreeNode> stack = new Stack<TreeNode>();\n TreeNode node = root;\n \n if (node != null)\n stack.Push(node);\n \n // visit > left > right\n while (stack.Count > 0) {\n node = stack.Pop();\n preorder.Add(node.val); // Visit\n \n if (node.right != null) { // Push right\n stack.Push(node.right);\n }\n \n if (node.left != null) { // Push left\n stack.Push(node.left);\n }\n \n }\n \n return preorder;\n }\n}\n```\n\n**Recursive Approach**\n* Recursion is the straightforward approach and mimics the concept of `visit > left > right` for `preorder` traversals\n* We need to pass the `list` as a parameter so we can add the values of the visited nodes to it\n* **Alternative approach**: instead of passing `preorder` list, you can make it a `global` field. \n* **Another approach**: final approach would be for the helper function to `return` the `preorder` list\n\n``` csharp\npublic class Solution {\n public IList<int> PreorderTraversal(TreeNode root) { \n IList<int> preorder = new List<int>();\n PreOrder(preorder, root);\n \n return preorder;\n }\n \n private void PreOrder(IList<int> list, TreeNode node) {\n if (node == null) return;\n \n list.Add(node.val); // Visit\n PreOrder(list, node.left); // Left\n PreOrder(list, node.right); // Right\n }\n}\n``` | 9 | 0 | ['Stack', 'Recursion', 'Iterator', 'C#'] | 1 |
binary-tree-preorder-traversal | Extremely Simple. Morris Traversal. Pre/In/Post Order Summary. | extremely-simple-morris-traversal-preinp-b8ui | There are a lot of introductions about how Morris Traversal works. It is a beautiful algorithm which takes only O(1) space complexity while still maintaining O( | h_cong | NORMAL | 2020-12-06T10:01:51.629492+00:00 | 2020-12-06T10:01:51.629537+00:00 | 547 | false | There are a lot of introductions about how Morris Traversal works. It is a beautiful algorithm which takes only O(1) space complexity while still maintaining O(n) time complexity. Here I summarized how Morris Traversal is implemented w.r.t. all three orders. \n\n**Pre-Order:**\n```\ndef preorderTraversal(self, root: TreeNode) -> List[int]:\n \n\tres = []\n\n\twhile root:\n\t\tif root.left:\n\t\t\ttemp = root.left\n\t\t\twhile temp.right and temp.right != root:\n\t\t\t\ttemp = temp.right\n\t\t\tif not temp.right:\n\t\t\t\tres.append(root.val) \n\t\t\t\ttemp.right = root\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\ttemp.right = None \n\t\t\t\troot = root.right\n\t\telse:\n\t\t\tres.append(root.val)\n\t\t\troot = root.right\n\n\treturn res\n```\n**In-Order**: \n\nCompared to Pre-Order implementation, the change is just one line as maked "***"\n```\ndef inorderTraversal(self, root: TreeNode) -> List[int]:\n \n\tres = []\n\n\twhile root:\n\t\tif root.left:\n\t\t\ttemp = root.left\n\t\t\twhile temp.right and temp.right != root:\n\t\t\t\ttemp = temp.right\n\t\t\tif not temp.right:\n\t\t\t\ttemp.right = root\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\tres.append(root.val) # ***\n\t\t\t\ttemp.right = None\n\t\t\t\troot = root.right\n\t\telse:\n\t\t\tres.append(root.val)\n\t\t\troot = root.right\n\n\treturn res\n```\n**Post-Order:**\n\nI saw many implementations for the Post-Order to be very complex and hard to remember. Here I provide a simple version. It is very similar to the pre-order one, except that now we are doing everything reversely. By this I mean we go along the direction of right child and link the leftmost child on the right sub tree to the root. Then we leftappend the val to the result. \n\nTHAT`S IT!!\n```\ndef postorderTraversal(self, root: TreeNode) -> List[int]:\n\t\n\tres = deque()\n\n\twhile root:\n\t\tif root.right:\n\t\t\ttemp = root.right\n\t\t\twhile temp.left and temp.left != root:\n\t\t\t\ttemp = temp.left\n\t\t\tif not temp.left:\n\t\t\t\tres.appendleft(root.val)\n\t\t\t\ttemp.left = root\n\t\t\t\troot = root.right\n\t\t\telse:\n\t\t\t\ttemp.left = None\n\t\t\t\troot = root.left\n\t\telse:\n\t\t\tres.appendleft(root.val)\n\t\t\troot = root.left\n\n\treturn res\n```\n\nHope you like it. Cheers. | 9 | 0 | [] | 2 |
binary-tree-preorder-traversal | Simple Iterative Javascript Solution | simple-iterative-javascript-solution-by-pryqw | Of the three main types of binary tree traversals (inorder,preorder,postorder), I find preorder traversal the easiest to implement iteratively. You can just reu | knownfemme | NORMAL | 2018-10-03T09:02:30.207634+00:00 | 2018-10-03T09:02:30.207676+00:00 | 2,679 | false | Of the three main types of binary tree traversals (inorder,preorder,postorder), I find preorder traversal the easiest to implement iteratively. You can just reuse the dfs algorithm, but make sure you push the children onto the stack in such a way that the left child is processed before the right child.\n```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nvar preorderTraversal = function(root) {\n var stack = [];\n\t\t\n // We do not push the root node onto the stack if the root node is null. This way we will avoid\n // going into the while loop when the root is null and just return an empty array as the result. \n if(root !== null){\n stack.push(root);\n }\n \n // Initialize the result to an empty array \n var res = [];\n\t\t\n // Keep iterating while there is something on the stack\n while(stack.length > 0){\n var node = stack.pop();\n\t\t\t\t\n\t// Do the preorder processing\n res.push(node.val);\n\t\t\t\t\n // If there is a right child, push it onto the stack. \n if(node.right !== null){\n stack.push(node.right);\n }\n\t\t\t\t\n // If there is a left child, push it onto the stack. \n if(node.left !== null){\n stack.push(node.left);\n }\n }\n \n return res; \n};\n``` | 9 | 0 | [] | 0 |
binary-tree-preorder-traversal | Binary Tree PreOrder Traversal - Beats upto 100% of other's runtime | binary-tree-preorder-traversal-beats-upt-3dst | Basic Concept\n Describe your first thoughts on how to solve this problem. \nA PreOrder Traversal is done in the order Root-Left-Right . \n\n---\n\n# Code Walk | ak9807 | NORMAL | 2024-07-19T18:41:50.275800+00:00 | 2024-07-20T05:17:40.154579+00:00 | 1,313 | false | # Basic Concept\n<!-- Describe your first thoughts on how to solve this problem. -->\nA PreOrder Traversal is done in the order **Root-Left-Right** . \n\n---\n\n# Code Walk Through\n<!-- Describe your approach to solving the problem. -->\nLet\'s understand the code and approach.\n\n**Initializations**\n1. We initialize a stack which is going to hold our nodes in the preorder manner.\n\n2. An ArrayList is initialized that is going to be the final list .\n\nNow , if our root node is null , we need to handle that case as well .\nSo , we just return the empty output list .\n ```\nStack<TreeNode>stack = new Stack<>();\n List<Integer>output = new ArrayList<>();\n if(root==null)\n {\n return output;\n }\n```\n\nNow, we push our root node to the stack , since root has to be processed first.\nAnd use a loop to traverse until our stack becomes empty.\n\n```\nTreeNode current = stack.pop();\n output.add(current.val);\n\n if(current.right!=null)\n {\n stack.push(current.right);\n }\n\n if(current.left!=null)\n {\n stack.push(current.left);\n }\n\n```\nIn this part of the code , we set the current pointer with the popped element from the stack ( which was the root node itself) and then add it to the output list.\n\nthen we check if current node\'s right one is not null , we push that right node into the stack .\nSimilar steps with the current node\'s left child.\n\n**Why RightNode is processed before the LeftNode when the PreOrder Traversal is otherwise**?\n\n- because of stack\'s LIFO principle where the last element is popped first , so if we push left node after the right node , then left will get popped out from the stack first** . And then finally return the output list.\n---\n\n# Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. -->\n\n- Space complexity : $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n---\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n Stack<TreeNode>stack = new Stack<>();\n List<Integer>output = new ArrayList<>();\n if(root==null)\n {\n return output;\n }\n stack.push(root);\n\n while(!stack.isEmpty()){\n TreeNode current = stack.pop();\n output.add(current.val);\n\n if(current.right!=null)\n {\n stack.push(current.right);\n }\n\n if(current.left!=null)\n {\n stack.push(current.left);\n }\n }//while ends\n return output;\n }//function ends\n}//class ends\n``` | 8 | 0 | ['Stack', 'Tree', 'Depth-First Search', 'Binary Tree', 'Java'] | 0 |
binary-tree-preorder-traversal | Java || 👍Explained in Detail👍|| Simple & Fast Solution✅|| Recursive & Iterative | java-explained-in-detail-simple-fast-sol-a87y | I do my best everyday to give a clear explanation, so to help everyone improve their skills.\n\nIf you find this helpful, please \uD83D\uDC4D upvote this post a | cheehwatang | NORMAL | 2023-01-09T03:12:24.376079+00:00 | 2023-01-09T03:41:40.464648+00:00 | 1,222 | false | I do my best everyday to give a clear explanation, so to help everyone improve their skills.\n\nIf you find this **helpful**, please \uD83D\uDC4D **upvote** this post and watch my [Github Repository](https://github.com/cheehwatang/leetcode-java).\n\nThank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.\n\n---\n\n# Approach\n\nAlgorithm for Preorder(tree)\n 1. Visit the root.\n 2. Traverse the left subtree\n 3. Traverse the right subtree\n\nExample:\n\nSteps:\n1. At node 1 now, add root value 1 => Integers[1]\n2. At node 1 now, traverse the left node.\n3. At node 2 now, add root value 2 => Integers[1, 2]\n4. At node 2 now, traverse the left node.\n5. At node 4 now, add root value 4 => Integers[1, 2, 4]\n6. At node 4 now, traverse the left node. Since no left node (null), return to node 4.\n7. At node 4 now, traverse the right node. Since no right node (null), return to node 4, then node 2.\n8. At node 2 now, traverse the right node.\n9. At node 5 now, add root value 5 => Integers[1, 2, 4, 5]\n10. At node 5 now, traverse the left node. Since no left node (null), return to node 5.\n11. At node 5 now, traverse the right node. Since no right node (null), return to node 5, then node 2, then node 1.\n12. At node 1 now, traverse the riht node.\n13. At node 3 now, add root value 3 => Integers[1, 2, 4, 5, 3]\n14. At node 3 now, traverse the left node. Since no left node (null), return to node 3.\n15. At node 3 now, traverse the right node. Since no right node (null), end traversal.\n\nAs shown, each node here has the traversal sequence of root -> left -> right.\n\n---\n\n# Recursive Implementation:\n\n## Complexity\n- Time Complexity : O(n), \nwhere \'n\' is the number of nodes in the tree, as we are traversing every single node.\nHowever, this does not take into account the resizing of the array backing the LinkedList, depending on the size of nodes in the tree.\n\n- Space Complexity : O(n), \nwhere \'n\' is the number of nodes in the tree, as we are recording the value of every node into the List.\nThe recursive call stack only takes up the maximum space of tree height, which is smaller than \'n\'.\n\n## Java - With Explanation (Recursive)\n\n```\nclass Solution {\n\n // Wrapper method to set up and initialize the recursive function.\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> integerList = new LinkedList<>();\n integerList = preorderTraversal(root, integerList);\n return integerList;\n }\n\n // Recursive method.\n private List<Integer> preorderTraversal(TreeNode root, List<Integer> integerList) {\n // The base case, for when the root is null.\n if (root == null) return integerList;\n\n // For preorder traversal, we first visit the root and add the value of the root to the list.\n integerList.add(root.val);\n // Then, we visit the left node.\n preorderTraversal(root.left, integerList);\n // Lastly, we visit the right node.\n preorderTraversal(root.right, integerList);\n\n // Once done, we return the list.\n return integerList;\n }\n}\n```\n\n## Java - Clean Code (Recursive)\n\n```\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> integerList = new LinkedList<>();\n integerList = preorderTraversal(root, integerList);\n return integerList;\n }\n\n private List<Integer> preorderTraversal(TreeNode root, List<Integer> integerList) {\n if (root == null) return integerList;\n\n integerList.add(root.val);\n preorderTraversal(root.left, integerList);\n preorderTraversal(root.right, integerList);\n\n return integerList;\n }\n}\n```\n\n---\n\n# Iterative Implementation:\n\n## Complexity\n- Time Complexity : O(n), \nwhere \'n\' is the number of nodes in the tree, as we are traversing every single node.\nHowever, this does not take into account the resizing of the array backing the LinkedList, depending on the size of nodes in the tree.\n\n- Space Complexity : O(n), \nwhere \'n\' is the number of nodes in the tree, as we are recording the data of every node into the List.\nThe stack only takes up the maximum space of tree height, which is smaller than \'n\'.\n\n## Java - With Explanation (Iterative)\n\n```\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> integerList = new LinkedList<>();\n Stack<TreeNode> rightNodes = new Stack<>();\n\n while (root != null) {\n // First, we record the root.\n integerList.add(root.val);\n\n // If right node is available, push the right node into the Stack first.\n // We will pop it later we are done with the left nodes.\n if (root.right != null) {\n rightNodes.push(root.right);\n }\n\n // Continue to traverse to the left, while recording each subtree root nodes,\n // and pushing the subtree right nodes into the stack.\n // Once reaches a leaf node, pop the right nodes and continue.\n root = root.left;\n if (root == null && !rightNodes.isEmpty()) {\n root = rightNodes.pop();\n }\n }\n // Fully traversed the tree.\n return integerList;\n }\n}\n```\n\n## Java - Clean Code (Iterative)\n\n```\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> integerList = new LinkedList<>();\n Stack<TreeNode> rightNodes = new Stack<>();\n\n while (root != null) {\n integerList.add(root.val);\n\n if (root.right != null) {\n rightNodes.push(root.right);\n }\n\n root = root.left;\n if (root == null && !rightNodes.isEmpty()) {\n root = rightNodes.pop();\n }\n }\n return integerList;\n }\n}\n``` | 8 | 0 | ['Binary Search', 'Stack', 'Depth-First Search', 'Binary Tree', 'Java'] | 0 |
binary-tree-preorder-traversal | Iterative Solution with Stack ✅Beats 100% solution in time✅ | iterative-solution-with-stack-beats-100-5x2oi | Intuition\nWe have to do preorder traversal where we print value for root then we go for it\'s left sub tree and in the last we go for right sub tree of the roo | deleted_user | NORMAL | 2023-01-09T03:02:31.812109+00:00 | 2023-01-09T03:02:31.812147+00:00 | 630 | false | # Intuition\nWe have to do preorder traversal where we print value for root then we go for it\'s left sub tree and in the last we go for right sub tree of the root.\n\nstack is the LIFO(Last in first out data structure) so we can use this property\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1-Add root of the tree in the stack and traverse till stack becomes empty \n2-Remove top of the stack and store it in the variable called rem now add value of rem in our List\n3-If there exist right child of the remove node (rem) then add it to the stack and then do same with the left child of the root \n\n(Here we are adding right child first and left child later so that while we will remove the element, left child will be poped out first )\n\n# Complexity\n- Time complexity:O(N)\nWe are Traversing all elements of the tree ones so that time complexity will be O(n)<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(H)\n-Here H is the height of the tree (Stack will not store all n elements at once)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n if(root==null){\n return new ArrayList<>();\n }\n List<Integer>l = new ArrayList<>();\n Stack<TreeNode>st = new Stack<>();\n st.push(root);\n while(st.isEmpty()==false){\n TreeNode rem = st.pop();\n l.add(rem.val);\n if(rem.right!=null){\n st.push(rem.right);\n }\n if(rem.left!=null){\n st.push(rem.left);\n }\n }\n return l;\n }\n}\n```\nI hope you understand the solution, have a great day ahead.\nHar Har Mahadev\uD83D\uDD49\uFE0F\u2764\uFE0F,\n | 8 | 1 | ['Java'] | 0 |
binary-tree-preorder-traversal | Iterative Preorder Travesal using Stack | iterative-preorder-travesal-using-stack-8q6bo | Intuition\nIterative Preorder Travesal using Stack\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\nO(n)\n\n | keyuraval | NORMAL | 2023-01-02T07:38:52.581296+00:00 | 2023-01-02T07:39:26.660221+00:00 | 2,433 | false | # Intuition\nIterative Preorder Travesal using Stack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n if(root==NULL){\n return preorder;\n }\n stack<TreeNode*> st;\n st.push(root);\n while(!st.empty()){\n root=st.top();\n st.pop();\n preorder.push_back(root->val);\n\n if(root->right!=NULL){\n st.push(root->right);\n }\n if(root->left!=NULL){\n st.push(root->left);\n }\n }\n return preorder;\n }\n};\n\n``` | 8 | 0 | ['C++'] | 3 |
binary-tree-preorder-traversal | C++ solutions | c-solutions-by-infox_92-gqp6 | \nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n ListNode* cur_node = head;\n while (cur_node && cur_node->next) {\ | Infox_92 | NORMAL | 2022-11-18T11:49:34.728216+00:00 | 2022-11-18T11:49:34.728238+00:00 | 946 | false | ```\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n ListNode* cur_node = head;\n while (cur_node && cur_node->next) {\n ListNode* next_node = cur_node->next;\n if (cur_node->val == next_node->val)\n cur_node->next = next_node->next;\n else\n cur_node = next_node;\n }\n return head;\n }\n};\n``` | 8 | 0 | ['C', 'C++'] | 1 |
binary-tree-preorder-traversal | ✅striver's method || Upvote if you like ⬆️⬆️ | strivers-method-upvote-if-you-like-by-ra-2ae7 | \n\n# Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNod | ratnesh_maurya | NORMAL | 2022-11-12T11:47:42.743484+00:00 | 2022-12-08T19:06:35.344307+00:00 | 260 | false | \n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n if(root==NULL) return preorder;\n stack<TreeNode*> st;\n st.push(root);\n while(!st.empty())\n {\n\n root=st.top();\n st.pop();\n preorder.push_back(root->val);\n if(root->right!=NULL){\n st.push(root->right);\n }\n\n if(root->left!=NULL)\n {\n st.push(root->left);\n }\n\n }\n return preorder;\n \n }\n};\n``` | 8 | 1 | ['C++'] | 0 |
binary-tree-preorder-traversal | C++ solutiona || 0 ms 100% faster | c-solutiona-0-ms-100-faster-by-infox_92-8r3a | \nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (ro | Infox_92 | NORMAL | 2022-11-04T14:50:38.913938+00:00 | 2022-11-04T14:50:38.913970+00:00 | 1,198 | false | ```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> preorder;\n stack<TreeNode*> stack;\n if (root == NULL)\n return preorder;\n stack.push(root);\n while(!stack.empty()) {\n TreeNode* curr = stack.top();\n stack.pop();\n preorder.push_back(curr->val);\n if (curr->right != NULL)\n stack.push(curr->right);\n if (curr->left != NULL)\n stack.push(curr->left);\n }\n return preorder;\n }\n};\n``` | 8 | 0 | ['C', 'C++'] | 0 |
binary-tree-preorder-traversal | An Iterative 3-in-1 Template for Pre/In/Post-order Traversal | an-iterative-3-in-1-template-for-preinpo-b27j | Explanation\n\nOne only needs to write the code to the corresponding block.\n\nThe concept is exactly how recursion works.\nWe:\n\n- only traverse while the sta | lunluen | NORMAL | 2020-02-09T23:53:16.482398+00:00 | 2020-02-25T10:00:38.475536+00:00 | 999 | false | ## Explanation\n\nOne only needs to write the code to the corresponding block.\n\nThe concept is exactly how recursion works.\nWe:\n\n- only traverse while the stack is not empty. (#0)\n- push a left child to the stack right after a pre-order region. (#3)\n- push a right child to the stack right after an in-order region. (#6)\n- pop the stack right after a post-order region. (#8)\n\nAnd there are some implementation details:\n\n- If a traversal is not a in-order nor post-order traversal, it\'s a pre-order traversal. (#1)\n- Use a `while (true)` with a `if` statement inside to ensure `node` is not null outside the loop. (#2, #4)\n- If a node has no right child, the in-order operation and post-order operation happen simutaneously. (#5, #7)\n- `prev` is the last post-order traversed node. (#9)\n\n## Template\n\n```C++\n stack<TreeNode*> stack{};\n TreeNode* prev = nullptr;\n\n if (root)\n stack.push(root);\n while (not stack.empty()) { // #0\n TreeNode* node = stack.top();\n\n if (not prev or\n prev != node->left and prev != node->right) { // #1\n while (true) {\n // Pre-order region {\n // do_something();\n // }\n if (not node->left)\n break; // #2\n node = node->left;\n stack.push(node); // #3\n }\n }\n // #4\n if (not node->right or prev != node->right) { // #5\n // In-order region {\n // do_something();\n // }\n if (node->right)\n stack.push(node->right); // #6\n }\n\n if (not node->right or prev == node->right) { // #7\n // Post-order region {\n // do_something();\n // }\n stack.pop(); // #8\n prev = node; // #9\n }\n }\n```\n\n## A slightly changed version\n\n```C++\n stack<TreeNode*> stack{};\n TreeNode* node = root;\n TreeNode* prev = nullptr;\n\n while (node or not stack.empty()) {\n while (node) {\n // Pre-order region {\n // do_something();\n // }\n stack.push(node);\n node = node->left;\n }\n node = stack.top();\n\n if (not node->right or prev != node->right) {\n // In-order region {\n // do_something();\n // }\n if (node->right) {\n node = node->right;\n continue;\n }\n }\n\n if (not node->right or prev == node->right) {\n // Post-order region {\n // do_something();\n // }\n stack.pop();\n prev = node;\n node = nullptr;\n }\n }\n```\n\n## Examples\n\n### [Problem: Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)\n\n```C++\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> result{};\n stack<TreeNode*> stack{};\n TreeNode* prev = nullptr;\n\n if (root)\n stack.push(root);\n while (not stack.empty()) {\n TreeNode* node = stack.top();\n\n if (not prev or\n prev != node->left and prev != node->right) {\n while (true) {\n // Pre-order region {\n result.push_back(node->val); // <-------------- See here!\n // }\n if (not node->left)\n break;\n node = node->left;\n stack.push(node);\n }\n }\n\n if (not node->right or prev != node->right) {\n // In-order region {\n // do_something();\n // }\n if (node->right)\n stack.push(node->right);\n }\n\n if (not node->right or prev == node->right) {\n // Post-order region {\n // do_something();\n // }\n stack.pop();\n prev = node;\n }\n }\n return result;\n }\n};\n```\n\n### [Problem: Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)\n\n```C++\nclass Solution {\npublic:\n vector<int> inorderTraversal(TreeNode* root) {\n vector<int> result{};\n stack<TreeNode*> stack{};\n TreeNode* prev = nullptr;\n\n if (root)\n stack.push(root);\n while (not stack.empty()) {\n TreeNode* node = stack.top();\n\n if (not prev or\n prev != node->left and prev != node->right) {\n while (true) {\n // Pre-order region {\n // do_something();\n // }\n if (not node->left)\n break;\n node = node->left;\n stack.push(node);\n }\n }\n\n if (not node->right or prev != node->right) {\n // In-order region {\n result.push_back(node->val); // <-------------- See here!\n // }\n if (node->right)\n stack.push(node->right);\n }\n\n if (not node->right or prev == node->right) {\n // Post-order region {\n // do_something();\n // }\n stack.pop();\n prev = node;\n }\n }\n return result;\n }\n};\n```\n\n### [Problem: Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)\n\n```C++\nclass Solution {\npublic:\n vector<int> postorderTraversal(TreeNode* root) {\n vector<int> result{};\n stack<TreeNode*> stack{};\n TreeNode* prev = nullptr;\n\n if (root)\n stack.push(root);\n while (not stack.empty()) {\n TreeNode* node = stack.top();\n\n if (not prev or\n prev != node->left and prev != node->right) {\n while (true) {\n // Pre-order region {\n // do_something();\n // }\n if (not node->left)\n break;\n node = node->left;\n stack.push(node);\n }\n }\n\n if (not node->right or prev != node->right) {\n // In-order region {\n // do_something();\n // }\n if (node->right)\n stack.push(node->right);\n }\n\n if (not node->right or prev == node->right) {\n // Post-order region {\n result.push_back(node->val); // <-------------- See here!\n // }\n stack.pop();\n prev = node;\n }\n }\n return result;\n }\n};\n``` | 8 | 0 | ['Stack', 'Iterator', 'C++'] | 1 |
binary-tree-preorder-traversal | Java solution using stack | java-solution-using-stack-by-jeantimex-28yz | public List<Integer> postorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<Integer>();\n \n if (root == null)\n return r | jeantimex | NORMAL | 2015-07-08T00:28:15+00:00 | 2015-07-08T00:28:15+00:00 | 1,193 | false | public List<Integer> postorderTraversal(TreeNode root) {\n List<Integer> res = new ArrayList<Integer>();\n \n if (root == null)\n return res;\n \n Stack<TreeNode> stack = new Stack<TreeNode>();\n stack.push(root);\n \n while (!stack.isEmpty()) {\n TreeNode node = stack.pop();\n res.add(node.val);\n \n if (node.right != null)\n stack.push(node.right);\n \n if (node.left != null)\n stack.push(node.left);\n }\n \n return res;\n } | 8 | 0 | ['Java'] | 2 |
binary-tree-preorder-traversal | C# - iterative with Stack | c-iterative-with-stack-by-jdrogin-e6jz | public IList<int> PreorderTraversal(TreeNode root) {\n Stack<TreeNode> stack = new Stack<TreeNode>();\n List<int> list = new List<int>();\n | jdrogin | NORMAL | 2016-10-13T16:48:00.272000+00:00 | 2016-10-13T16:48:00.272000+00:00 | 834 | false | public IList<int> PreorderTraversal(TreeNode root) {\n Stack<TreeNode> stack = new Stack<TreeNode>();\n List<int> list = new List<int>();\n stack.Push(root);\n while (stack.Count() > 0)\n {\n TreeNode current = stack.Pop();\n if (current != null)\n {\n list.Add(current.val);\n stack.Push(current.right);\n stack.Push(current.left);\n }\n }\n \n return list;\n } | 8 | 0 | [] | 3 |
binary-tree-preorder-traversal | 144: Solution with step by step explanation | 144-solution-with-step-by-step-explanati-t2uj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo traverse a binary tree in a preorder fashion, we start from the root n | Marlen09 | NORMAL | 2023-02-19T12:27:27.785616+00:00 | 2023-02-19T12:27:27.785647+00:00 | 1,175 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo traverse a binary tree in a preorder fashion, we start from the root node, visit the left subtree, then the right subtree. We will use a stack to keep track of the nodes to be visited. We first push the root node onto the stack, and then while the stack is not empty, we pop the top node and visit it. If the popped node has a right child, we push it onto the stack. If the popped node has a left child, we push it onto the stack. We continue this process until the stack is empty.\n\nIn this code, we first check if the root is None. If it is, we return an empty list. Otherwise, we create an empty stack and add the root node to it. We also create an empty list to store the result.\n\nWe then start a while loop that continues until the stack is empty. In each iteration of the loop, we pop the top node from the stack and add its value to the result list. We then check if the popped node has a right child. If it does, we push the right child onto the stack. We then check if the popped node has a left child. If it does, we push the left child onto the stack.\n\nAfter the loop ends, we return the result list. This will contain the values of the nodes in preorder traversal order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n stack = [root]\n result = []\n while stack:\n node = stack.pop()\n result.append(node.val)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n return result\n\n``` | 7 | 0 | ['Tree', 'Depth-First Search', 'Binary Tree', 'Python', 'Python3'] | 0 |
binary-tree-preorder-traversal | ✔️ 0ms | explained easy solution | C++ | 0ms-explained-easy-solution-c-by-coding_-07f4 | Approach\nIn this question we need to traverse or move through this tree in pre order traversal\n\nFirst the root node, then the next node (left sibling, or lef | coding_menance | NORMAL | 2023-01-09T04:41:51.695262+00:00 | 2023-01-09T04:41:51.695300+00:00 | 982 | false | # Approach\nIn this question we need to traverse or move through this tree in pre order traversal\n\nFirst the root node, then the next node (left sibling, or left node) and after all the left nodes are exhausted on the left subtree, we go back on e node and check the right node or right sibling. Again when all nodes are done on that level we go back one level and repeat the same process unless we have reached the root back again; and then we start traversing the right sub tree, but here too we first go through the left siblings first and then the right siblings.\n\n```\nclass Solution {\npublic:\n void traverse(TreeNode* root, vector<int>& v) {\n if (root==NULL) return; // if node is null there is nothing more to check\n v.push_back(root->val); // We first add the node we\'re visiting to the output vector\n traverse(root->left, v); // Now let\'s move through the left siblings\n traverse(root->right, v); // After the left siblings are done with, we check for the right siblings as we start going back\n }\n\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> v;\n traverse(root, v);\n return v;\n }\n};\n```\n\n\n*Upvote this solution, as it might have helped you :)* | 7 | 0 | ['C++'] | 0 |
binary-tree-preorder-traversal | ✅A Classic Approach to Preorder Tree Traversal: A Recursive Solution | Beats 100% Time [C#]✅ | a-classic-approach-to-preorder-tree-trav-426g | The PreorderTraversal function is the public interface for the algorithm, and it accepts the root node of a binary tree as an argument. It creates an empty list | shukhratutaboev | NORMAL | 2023-01-09T04:27:32.898345+00:00 | 2023-01-09T04:30:10.441864+00:00 | 1,638 | false | The PreorderTraversal function is the public interface for the algorithm, and it accepts the root node of a binary tree as an argument. It creates an empty list to store the result of the traversal, and then calls the PreorderTraversalRecursive function on the root node to perform the actual traversal.\n\nThe PreorderTraversalRecursive function has the following steps:\n\nIf the node is null, it returns immediately.\nIt adds the value of the node (node.val) to the list.\nIt calls itself recursively on the left child of the node (node.left).\nIt calls itself recursively on the right child of the node (node.right).\nThis way, the function traverses the tree in a depth-first fashion, visiting the root node first, then the left subtree, and finally the right subtree.\n\nWhen the traversal is complete, the PreorderTraversal function returns the list containing the values of the nodes in the order they were visited.\n\n# Approach\nDFS\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution\n{\n public IList<int> PreorderTraversal(TreeNode root)\n {\n var list = new List<int>();\n PreorderTraversalRecursive(root, list);\n return list;\n }\n\n private void PreorderTraversalRecursive(TreeNode node, List<int> list)\n {\n if (node == null) return;\n list.Add(node.val);\n PreorderTraversalRecursive(node.left, list);\n PreorderTraversalRecursive(node.right, list);\n }\n}\n```\n\nIf you found my solution helpful, please consider upvoting it to let others know! | 7 | 0 | ['C#'] | 0 |
binary-tree-preorder-traversal | DAILY LEETCODE SOLUTION || EASY C++ SOLUTION | daily-leetcode-solution-easy-c-solution-gx8f2 | \n//PreorderTraversal Using Recurrsion\nclass Solution {\npublic:\n vector<int> ans;\n void preorder(TreeNode* root)\n {\n if(root==NULL)\n | pankaj_777 | NORMAL | 2023-01-09T00:04:56.110832+00:00 | 2023-01-09T12:29:50.355543+00:00 | 1,930 | false | ```\n//PreorderTraversal Using Recurrsion\nclass Solution {\npublic:\n vector<int> ans;\n void preorder(TreeNode* root)\n {\n if(root==NULL)\n {\n return ;\n }\n ans.push_back(root->val);\n preorder(root->left);\n preorder(root->right);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n preorder(root);\n return ans;\n }\n};\n```\n```\n//Preorder Traversal Using Morris Traversal\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n TreeNode* curr=root;\n while(curr){\n if(!curr->left){\n ans.push_back(curr->val);\n curr=curr->right;\n }\n else{\n TreeNode* pre=curr->left;\n while(pre->right&&pre->right!=curr){\n pre=pre->right;\n }\n if(pre->right==NULL){\n pre->right=curr;\n ans.push_back(curr->val);\n curr=curr->left;\n }\n else{\n pre->right=NULL;\n curr=curr->right;\n }\n }\n }\n return ans;\n }\n};\n``` | 7 | 0 | ['Recursion', 'Binary Tree'] | 1 |
binary-tree-preorder-traversal | C++ | Inorder / Preorder / Postorder All 3 solution | 0ms faster than 100% | c-inorder-preorder-postorder-all-3-solut-a766 | You can observe there is just a minimal diffrence in all 3 ,i.e, it\'s just the way of filling vector while calling fill function. \nInorder Traversal : \n\ncl | vaibhav4859 | NORMAL | 2021-10-25T13:09:57.943811+00:00 | 2021-10-25T13:09:57.943842+00:00 | 638 | false | You can observe there is just a minimal diffrence in all 3 ,i.e, it\'s just the way of filling vector while calling fill function. \n***Inorder Traversal :*** \n```\nclass Solution {\npublic:\n vector<int> ans;\n void fill(TreeNode* root){\n if(!root)\n return;\n fill(root->left);\n ans.push_back(root->val); // Inorder\n fill(root->right);\n }\n \n vector<int> inorderTraversal(TreeNode* root) {\n fill(root);\n return ans;\n }\n};\n```\n\n***Preorder Traversal :***\n```\nclass Solution {\npublic:\n vector<int> ans;\n void fill(TreeNode* root){\n if(!root)\n return;\n ans.push_back(root->val); // Preoder\n fill(root->left);\n fill(root->right);\n }\n \n vector<int> preorderTraversal(TreeNode* root) {\n fill(root);\n return ans;\n }\n};\n```\n\n***Postorder Traversal :***\n\n```\nclass Solution {\npublic:\n vector<int> ans;\n void fill(TreeNode* root){\n if(!root)\n return;\n fill(root->left);\n fill(root->right);\n ans.push_back(root->val); /// Postorder\n }\n \n vector<int> postorderTraversal(TreeNode* root) {\n fill(root);\n return ans;\n }\n};\n```\nHope you liked it , kindly upvote !!\n\nHappy Coding \uD83E\uDD17 | 7 | 0 | ['Recursion', 'C', 'C++'] | 1 |
binary-tree-preorder-traversal | Three types of solution(recursion, iterative,morris) 100% faster c++ | three-types-of-solutionrecursion-iterati-wocg | All Three types of solutions: \n1. Recursion => TC - O(N) and SC - (N)\n2. Iterative => TC - O(N) and SC - (N)\n3. Morris Traversal => TC - O(N) and SC - (1)\n\ | akbhobhiya | NORMAL | 2021-07-29T06:26:38.057713+00:00 | 2021-07-29T06:27:44.882910+00:00 | 507 | false | ## All Three types of solutions: \n1. Recursion => TC - O(N) and SC - (N)\n2. Iterative => TC - O(N) and SC - (N)\n3. Morris Traversal => TC - O(N) and SC - (1)\n\n#### **Using recursion (4ms time) TC - O(N) and SC - O(N)**\n```\nclass Solution {\npublic:\n vector<int> ans;\n vector<int> preorderTraversal(TreeNode* root) {\n if(root==NULL)return ans;\n\t\t ans.push_back(root->val);\n preorderTraversal(root->left);\n preorderTraversal(root->right);\n return ans;\n }\n}; \n```\n#### Iterative method using Stack(0ms) \n\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n stack<TreeNode*> store;\n while(!store.empty() || root){\n if(root){\n ans.push_back(root->val); // print root\n if(root->right){ \n store.push(root->right);//put into stack so that after print left we can go right\n }\n root=root->left; // make root of left sub tree;\n }\n else{\n root=store.top();//if root is null that means left tree is not there; we pop the node\n store.pop();\n }\n }\n\t\t return ans;\n }\n};\n```\n\n#### **Morris Traversal in O(1) space and O(N) time**\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n while(root){\n if(root->left==NULL){ // if left not there, add root to answer\n ans.push_back(root->val);\n root=root->right; // go to right (bcz left is not there)\n }\n else{ // left is there then find the predecessor of root(for tracking to root after visiting left)\n TreeNode* temp = root;\n temp=temp->left;\n while(temp->right && temp->right!=root){\n temp = temp->right;\n }\n if(temp->right==NULL){ //link predecessor->right to root(to go to root)\n temp->right=root;\n ans.push_back(root->val); // push the root node (we are going in left direction so before that add root as ans);\n root=root->left;// goto left direction \n }\n else{ // if predecessor is linked with root that means left subtree is already visited; goto right \n temp->right=NULL;\n root=root->right;\n } \n }\n }\n return ans;\n }\n};\n```\n\n### **If you like the solution please upvote it. Thanks**\n | 7 | 0 | ['Recursion', 'C', 'Iterator', 'C++'] | 1 |
binary-tree-preorder-traversal | C Solution | c-solution-by-robinsgv-h5g2 | \n\nint nodeCount(struct TreeNode* root) {\n if (NULL == root)\n return 0;\n \n return (nodeCount(root->left)+ nodeCount(root->right)) + 1;\n}\n | robinsgv | NORMAL | 2021-02-06T18:50:14.556142+00:00 | 2021-02-06T18:50:14.556174+00:00 | 685 | false | ```\n\nint nodeCount(struct TreeNode* root) {\n if (NULL == root)\n return 0;\n \n return (nodeCount(root->left)+ nodeCount(root->right)) + 1;\n}\n\nvoid preorder(struct TreeNode* root, int *res, int *size) {\n if(NULL == root)\n return;\n \n res[(*size)++] = root->val;\n preorder(root->left, res, size);\n preorder(root->right, res, size);\n}\n\nint* preorderTraversal(struct TreeNode* root, int* returnSize){\n int lev = nodeCount(root);\n \n int *result =(int*)malloc(sizeof(int)*lev+1);\n *returnSize = 0;\n\n preorder(root, result, returnSize);\n \n return result;\n}\n``` | 7 | 0 | [] | 2 |
binary-tree-preorder-traversal | C solution | c-solution-by-gsingh1629-e8wn | void travel(struct TreeNode root,int arr,int size){\n if(root==NULL)\n return;\n arr[(size)++]=root->val;\n travel(root->left,arr,size);\n tr | GSingh1629 | NORMAL | 2020-10-16T14:17:13.059558+00:00 | 2020-10-16T14:17:13.059606+00:00 | 1,216 | false | void travel(struct TreeNode *root,int *arr,int *size){\n if(root==NULL)\n return;\n arr[(*size)++]=root->val;\n travel(root->left,arr,size);\n travel(root->right,arr,size);\n}\nint* preorderTraversal(struct TreeNode* root, int* returnSize){\n *returnSize=0;\n int *arr=(int *)malloc(100*sizeof(int));\n travel(root,arr,returnSize);\n return arr;\n} | 7 | 3 | ['Recursion', 'C'] | 2 |
binary-tree-preorder-traversal | javascript | javascript-by-yinchuhui88-b08t | \nvar preorderTraversal = function(root) {\n let result = [];\n dfs(root);\n \n function dfs(root) {\n if(root != null){\n result. | yinchuhui88 | NORMAL | 2018-10-11T07:01:29.576406+00:00 | 2018-10-11T07:01:29.576476+00:00 | 1,473 | false | ```\nvar preorderTraversal = function(root) {\n let result = [];\n dfs(root);\n \n function dfs(root) {\n if(root != null){\n result.push(root.val);\n dfs(root.left);\n dfs(root.right);\n }\n }\n return result;\n};\n``` | 7 | 1 | [] | 0 |
binary-tree-preorder-traversal | Simple iterative and recursive solutions | simple-iterative-and-recursive-solutions-7bbf | \nSolution 1, Iterative\n\n def preorderTraversal(self, root):\n stack, ans =[root], []\n while stack:\n node = stack.pop(-1)\n | cmc | NORMAL | 2016-01-16T11:11:59+00:00 | 2016-01-16T11:11:59+00:00 | 1,511 | false | \n**Solution 1, Iterative**\n\n def preorderTraversal(self, root):\n stack, ans =[root], []\n while stack:\n node = stack.pop(-1)\n while node:\n if node.right:\n stack.append(node.right)\n ans.append(node.val)\n node=node.left\n return ans\n\n<br><br>\n\n**Solution 2 , Recursive**\n\n def preorderTraversal(self, root):\n def DFS(node):\n if node:\n ans.append(node.val)\n DFS(node.left)\n DFS(node.right)\n ans = []\n DFS(root)\n return ans | 7 | 0 | ['Python'] | 1 |
binary-tree-preorder-traversal | ✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 100%🔥|| Beginner friendly💀💯 | simple-code-easy-to-understand-beats-100-d1h6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | atishayj4in | NORMAL | 2024-07-25T19:47:03.402668+00:00 | 2024-08-01T20:04:38.677371+00:00 | 811 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List<Integer> ans = new ArrayList<>();\n public List<Integer> preorderTraversal(TreeNode root) {\n preorder(root);\n return ans;\n }\n public void preorder(TreeNode node){\n if(node==null){\n return;\n }\n ans.add(node.val);\n preorder(node.left);\n preorder(node.right);\n }\n}\n```\n\n | 6 | 0 | ['Stack', 'Tree', 'Depth-First Search', 'C', 'Binary Tree', 'Python', 'C++', 'Java'] | 1 |
binary-tree-preorder-traversal | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-c72n | Intuition\n\n\n\n\n\n\nJavaScript []\n//JavaScript Code\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = | Edwards310 | NORMAL | 2024-04-17T04:12:26.073673+00:00 | 2024-08-26T08:03:20.396434+00:00 | 684 | false | # Intuition\n\n\n\n\n\n\n```JavaScript []\n//JavaScript Code\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nvar preorderTraversal = function(root) {\n const arr = []\n var preOrder = ((root) => {\n if(!root)\n return\n \n arr.push(root.val)\n preOrder(root.left)\n preOrder(root.right)\n return\n })\n preOrder(root)\n return arr\n};\n```\n```C++ []\n//C++ Code\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),\n * right(right) {}\n * };\n */\nclass Solution {\n vector<int> ans;\n\npublic:\n void preorder(TreeNode* root, vector<int>& ans) {\n if (root) {\n ans.push_back(root->val);\n preorder(root->left, ans);\n preorder(root->right, ans);\n }\n return;\n }\n vector<int> preorderTraversal(TreeNode* root) {\n preorder(root, ans);\n return ans;\n }\n};\n```\n```python3 []\n#Python3 Code\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n\n def _preorder(root):\n if root:\n res.append(root.val)\n _preorder(root.left)\n _preorder(root.right)\n return\n \n _preorder(root)\n return res\n```\n```C []\n//C Code\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * struct TreeNode *left;\n * struct TreeNode *right;\n * };\n */\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nvoid preorder(struct TreeNode* root, int* arr, int* returnSize) {\n if (root) {\n arr[(*returnSize)++] = root->val;\n preorder(root->left, arr, returnSize);\n preorder(root->right, arr, returnSize);\n }\n return;\n}\nint* preorderTraversal(struct TreeNode* root, int* returnSize) {\n int* arr = (int*)malloc(sizeof(int) * 100);\n *returnSize = 0;\n preorder(root, arr, returnSize);\n return arr;\n free(arr);\n}\n```\n```Java []\n//Java Code\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List<Integer> ans = new ArrayList<>();\n\n private void preorder(TreeNode root) {\n if (root == null)\n return;\n ans.add(root.val);\n preorder(root.left);\n preorder(root.right);\n return;\n }\n\n public List<Integer> preorderTraversal(TreeNode root) {\n preorder(root);\n return ans;\n }\n}\n```\n```python []\n#Pytho Code\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n res = []\n\n def _preorder(root):\n if root:\n res.append(root.val)\n _preorder(root.left)\n _preorder(root.right)\n return\n \n _preorder(root)\n return res\n```\n```C# []\n//C# Code\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public int val;\n * public TreeNode left;\n * public TreeNode right;\n * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\npublic class Solution {\n List<int> res = new List<int>();\n private void preOrder(TreeNode root){\n if(root == null)\n return;\n \n res.Add(root.val);\n preOrder(root.left);\n preOrder(root.right);\n }\n public IList<int> PreorderTraversal(TreeNode root) {\n preOrder(root);\n return res;\n }\n}\n```\n---\n1. **Also Check out the Same Questions Like this.**\n- ***LC _ 94 Binary Tree Inorder Traversal*** https://leetcode.com/problems/binary-tree-inorder-traversal/solutions/4328091/faster-lesser-c-python3-java-c-python-explained-beats\n- ***LC _ 145 Binary PostOrder Traversal*** https://leetcode.com/problems/binary-tree-postorder-traversal/solutions/5039124/easiest-c-python3-c-java-c-python-beats-simplified-version\n---\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n) -- no. of nodes\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List<Integer> ans = new ArrayList<>();\n\n private void preorder(TreeNode root) {\n if (root == null)\n return;\n ans.add(root.val);\n preorder(root.left);\n preorder(root.right);\n return;\n }\n\n public List<Integer> preorderTraversal(TreeNode root) {\n preorder(root);\n return ans;\n }\n}\n```\n## Please upvote if it\'s useful for you ... If it\'s helpful for you.. Then Please upvote my solution that will be a great help for me and motivates me to do better..\n\n | 6 | 0 | ['Stack', 'Depth-First Search', 'C', 'Binary Tree', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 2 |
binary-tree-preorder-traversal | DFS pre order. JS | dfs-pre-order-js-by-hanbi58-0cqb | Approach\nDepth first search.\n\nT: O(n) S: O(n)\n\n\n\n# Code\n\nvar preorderTraversal = function (root, arr = []) {\n DFS(root);\n return arr;\n function | hanbi58 | NORMAL | 2023-01-09T00:04:33.998498+00:00 | 2023-01-09T01:03:01.591770+00:00 | 829 | false | # Approach\nDepth first search.\n\nT: O(n) S: O(n)\n\n\n\n# Code\n```\nvar preorderTraversal = function (root, arr = []) {\n DFS(root);\n return arr;\n function DFS(node) {\n if (!node) return;\n arr.push(node.val);\n DFS(node.left);\n DFS(node.right);\n }\n};\n\n```\n\n\nor\n\n# Code\n```\nvar preorderTraversal = function (root, arr = []) {\n if (!root) return [];\n arr.push(node.val);\n preorderTraversal(root.left, arr);\n preorderTraversal(root.right, arr);\n return arr;\n}\n```\nor\n# Code\n```\nvar preorderTraversal = function (root, arr = []) {\n if (!root) return arr;\n return [root.val,...preorderTraversal(root.left, arr),...preorderTraversal(root.right, arr)];\n};\n```\n\n | 6 | 0 | ['JavaScript'] | 0 |
binary-tree-preorder-traversal | C++ Easy Solution | c-easy-solution-by-hemant_1451-vpnf | \n# Complexity\n- Time complexity : O(N)\n\n- Space complexity : O(1), if we don\u2019t consider the size of the stack for function. Otherwise, O(H) where H is | Hemant_1451 | NORMAL | 2023-01-06T14:02:47.494920+00:00 | 2023-01-06T14:02:47.494962+00:00 | 1,504 | false | \n# Complexity\n- Time complexity : $$O(N)$$\n\n- Space complexity : $$O(1)$$, if we don\u2019t consider the size of the stack for function. Otherwise, $$O(H)$$ where H is the height of the tree. \n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<int>res;\n vector<int> preorderTraversal(TreeNode* root) {\n if(root!=NULL)\n {\n res.push_back(root->val);\n preorderTraversal(root->left);\n preorderTraversal(root->right); \n }\n return res;\n }\n};\n``` | 6 | 0 | ['Tree', 'Binary Tree', 'C++'] | 1 |
binary-tree-preorder-traversal | 3 Approaches in C++ || Recursive, Iterative, Morris Traversal | 3-approaches-in-c-recursive-iterative-mo-ymjl | Recursive Approach:\n\nvoid help(TreeNode* root, vector<int>& ans)\n {\n if(root == NULL)\n return;\n ans.push_back(root->val);\n | diba_lc | NORMAL | 2022-07-17T09:00:18.657860+00:00 | 2022-07-17T09:00:18.657913+00:00 | 143 | false | **Recursive Approach:**\n````\nvoid help(TreeNode* root, vector<int>& ans)\n {\n if(root == NULL)\n return;\n ans.push_back(root->val);\n help(root->left, ans);\n help(root->right, ans);\n }\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n help(root, ans);\n return ans;\n }\n````\n\n-------------------------------------------------------------------------------------------------------\n**Iterative Approach:**\n````\nvector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n if(root==NULL) return ans;\n stack<TreeNode*> st;\n st.push(root);\n while(!st.empty())\n {\n root = st.top();\n st.pop();\n ans.push_back(root->val);\n if(root->right!=NULL)\n {\n st.push(root->right);\n }\n if(root->left!=NULL)\n {\n st.push(root->left);\n }\n }\n return ans;\n }\n````\n\n-------------------------------------------------------------------------------------------------------\n**Morris Traversal :**\n````\nvector<int> preorderTraversal(TreeNode* root) {\n vector<int> ans;\n TreeNode *node = root;\n while(node != NULL)\n {\n if(node->left == NULL) \n {\n ans.push_back(node->val);\n node = node->right;\n }\n else\n {\n TreeNode *prev = node->left;\n while(prev->right && prev->right != node)\n {\n prev = prev->right;\n }\n if(prev->right == NULL)\n {\n prev->right = node;\n ans.push_back(node->val);\n node = node->left;\n }\n else\n {\n prev->right = NULL;\n node = node->right;\n }\n }\n }\n return ans;\n }\n````\n\n**One Request : Please do upvote if you found these solutions helpful. Thanks in advance!** | 6 | 0 | [] | 0 |
binary-tree-preorder-traversal | [JAVA] standard iterative solution | java-standard-iterative-solution-by-juga-p2s8 | \nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n ArrayList<Integer> ans = new ArrayList<Integer>();\n if(root == null) | Jugantar2020 | NORMAL | 2022-07-06T21:12:39.421661+00:00 | 2022-07-06T21:12:39.421713+00:00 | 407 | false | ```\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n ArrayList<Integer> ans = new ArrayList<Integer>();\n if(root == null) return ans;\n \n Stack<TreeNode> st = new Stack<TreeNode>();\n st.push(root);\n \n while(!st.isEmpty()) {\n TreeNode cur = st.pop(); \n ans.add(cur.val);\n \n if(cur.right != null) st.push(cur.right);\n if(cur.left != null) st.push(cur.left);\n }\n return ans;\n }\n}\n```\n# KINDLY UPVOTE IF IT WAS HELPFULL | 6 | 0 | ['Stack', 'Binary Tree', 'Iterator', 'Java'] | 0 |
binary-tree-preorder-traversal | 100 percent faster || easy to understand | 100-percent-faster-easy-to-understand-by-v9tz | class Solution {\n private : vectorres;\n void preorder(TreeNode root, vector&res)\n {\n if(root==NULL)\n return;\n res.push_b | Shivam_sahal | NORMAL | 2022-04-23T21:23:56.340138+00:00 | 2022-04-23T21:23:56.340171+00:00 | 506 | false | class Solution {\n private : vector<int>res;\n void preorder(TreeNode *root, vector<int>&res)\n {\n if(root==NULL)\n return;\n res.push_back(root->val);\n preorder(root->left,res);\n preorder(root->right,res);\n return;\n }\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n \n preorder(root,res);\n return res;\n \n }\n}; | 6 | 0 | ['C'] | 3 |
binary-tree-preorder-traversal | Simple Python solution (Recursive and Iterative Both) | simple-python-solution-recursive-and-ite-1gdw | Iterative approach using stack:\n\ndef preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans=[]\n if root==None:\n retu | thakur_01 | NORMAL | 2022-03-13T14:57:23.884168+00:00 | 2022-03-13T14:59:30.229169+00:00 | 323 | false | **Iterative approach using stack:**\n```\ndef preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans=[]\n if root==None:\n return None\n stack=[root]\n while len(stack)>0:\n temp=stack.pop(-1)\n ans.append(temp.val)\n if temp.right!=None:\n stack.append(temp.right)\n if temp.left!=None:\n stack.append(temp.left)\n return ans\n```\n\n**Recursive approach:**\n```\ndef preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tans=[]\n def preorder(root):\n if root==None:\n return None\n ans.append(root.val)\n preorder(root.left)\n preorder(root.right)\n preorder(root)\n return ans\n``` | 6 | 0 | ['Binary Tree', 'Python'] | 0 |
binary-tree-preorder-traversal | Python3 | easiest solution | python3-easiest-solution-by-anilchouhan1-ktih | \nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n \n if root:\n res+= [roo | Anilchouhan181 | NORMAL | 2022-02-12T13:01:32.505616+00:00 | 2022-02-12T13:01:49.673791+00:00 | 505 | false | ```\nclass Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n \n if root:\n res+= [root.val]\n res+= self.preorderTraversal(root.left)\n res+= self.preorderTraversal(root.right)\n return res\n``` | 6 | 0 | ['Python', 'Python3'] | 1 |
binary-tree-preorder-traversal | Python 20ms Classic Implementation | python-20ms-classic-implementation-by-ra-4skr | Runtime: 20 ms, faster than 98.55% of Python3 online submissions for Binary Tree Preorder Traversal.\nMemory Usage: 14.1 MB, less than 99.97% of Python3 online | ragav_1302 | NORMAL | 2020-10-09T17:29:00.960377+00:00 | 2020-10-09T17:36:44.336539+00:00 | 476 | false | Runtime: 20 ms, faster than 98.55% of Python3 online submissions for Binary Tree Preorder Traversal.\nMemory Usage: 14.1 MB, less than 99.97% of Python3 online submissions for Binary Tree Preorder Traversal.\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n self.ans=[]\n def preorder(root):\n if root is None:\n return\n self.ans.append(root.val)\n preorder(root.left)\n preorder(root.right)\n preorder(root)\n return self.ans\n``` | 6 | 0 | [] | 0 |
binary-tree-preorder-traversal | 👏🏻 Python Stack | DFS - 公瑾™ | python-stack-dfs-gong-jin-tm-by-yuzhoujr-9guw | 144. Binary Tree Preorder Traversal\n\n> \u7C7B\u578B\uFF1ADFS Stack | Recursive\n> Time Complexity O(n)\n> Space Complexity O(1)\n\n\n#### DFS Recursive\npytho | yuzhoujr | NORMAL | 2018-08-09T17:50:46.022872+00:00 | 2018-10-12T21:10:07.370304+00:00 | 745 | false | ### 144. Binary Tree Preorder Traversal\n```\n> \u7C7B\u578B\uFF1ADFS Stack | Recursive\n> Time Complexity O(n)\n> Space Complexity O(1)\n```\n\n#### DFS Recursive\n```python\nclass Solution(object):\n def preorderTraversal(self, root):\n self.res = []\n self.dfs(root)\n return self.res\n \n def dfs(self, root):\n if not root:\n return \n self.res.append(root.val)\n self.dfs(root.left)\n self.dfs(root.right) \n```\n\n#### Stack\n```python\nclass Solution(object):\n def preorderTraversal(self, root):\n res = []\n stack = [root]\n while stack:\n node = stack.pop()\n if node:\n res.append(node.val)\n stack.append(node.right)\n stack.append(node.left)\n return res\n``` | 6 | 0 | [] | 2 |
binary-tree-preorder-traversal | Elegant C++ iterative solution, 0ms, 10 lines | elegant-c-iterative-solution-0ms-10-line-99u7 | vector<int> preorderTraversal(TreeNode* root) {\n vector<int> result;\n stack<TreeNode*> q;\n q.push(root);\n while(!q.empty())\n | xlingcc | NORMAL | 2015-07-18T12:02:33+00:00 | 2015-07-18T12:02:33+00:00 | 951 | false | vector<int> preorderTraversal(TreeNode* root) {\n vector<int> result;\n stack<TreeNode*> q;\n q.push(root);\n while(!q.empty())\n {\n auto p = q.top();\n q.pop();\n if(p == NULL)\n {\n continue;\n }\n result.push_back(p->val);\n q.push(p->right);\n q.push(p->left);\n }\n \n return result;\n } | 6 | 0 | ['C++'] | 0 |
binary-tree-preorder-traversal | Java solution -- preorder Morris traversal | java-solution-preorder-morris-traversal-v8yga | ![preorder Morris traversal][1]\n\n public List preorderTraversal(TreeNode node) {\n List list = new ArrayList();\n \n while(node != nul | peng4 | NORMAL | 2015-09-29T18:50:52+00:00 | 2015-09-29T18:50:52+00:00 | 1,844 | false | ![preorder Morris traversal][1]\n\n public List<Integer> preorderTraversal(TreeNode node) {\n List<Integer> list = new ArrayList();\n \n while(node != null) {\n if(node.left == null) {\n list.add(node.val);\n node = node.right;\n }\n else {\n TreeNode nextNode = node.left;\n \n TreeNode p = nextNode;\n while(p.right != null) p = p.right;\n \n list.add(node.val);\n p.right = node.right;\n node = nextNode;\n }\n }\n return list;\n }\n\n\n [1]: http://images.cnitblog.com/blog/300640/201306/14221458-aa5f9e92cce743ccacbc735048133058.jpg | 6 | 0 | [] | 3 |
binary-tree-preorder-traversal | Accepted iterative simplest solution in Java using stack. | accepted-iterative-simplest-solution-in-uzecq | public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> list = new LinkedList<Integer>();\n | xpao24 | NORMAL | 2016-01-20T11:24:06+00:00 | 2016-01-20T11:24:06+00:00 | 973 | false | public class Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> list = new LinkedList<Integer>();\n Stack<TreeNode> stack = new Stack<TreeNode>();\n if(root!=null) stack.push(root);\n while(!stack.isEmpty()){\n TreeNode node = stack.pop();\n list.add(node.val);\n if(node.right!=null) stack.push(node.right);\n if(node.left!=null) stack.push(node.left);\n }\n return list;\n }\n } | 6 | 0 | ['Java'] | 1 |
binary-tree-preorder-traversal | Python one line | python-one-line-by-abyellow7511-sjeg | \nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n\n | abyellow7511 | NORMAL | 2017-02-20T13:03:11.647000+00:00 | 2017-02-20T13:03:11.647000+00:00 | 498 | false | ```\nclass Solution(object):\n def preorderTraversal(self, root):\n """\n :type root: TreeNode\n :rtype: List[int]\n """\n\n return [root.val]+ self.preorderTraversal(root.left) + self.preorderTraversal(root.right) if root else []\n``` | 6 | 0 | [] | 1 |
binary-tree-preorder-traversal | Conquering Preorder Traversal: The Ultimate Java and Python Guide! ⚔️ | conquering-preorder-traversal-the-ultima-ikra | 🌲 "The Tree Kingdom and the Legend of Preorder Traversal!" ⚔️Once upon a time, in the mystical land of Binary Trees, a wandering coder (that’s YOU! 💪) embarked | trivickram_1476 | NORMAL | 2025-04-01T06:03:01.522959+00:00 | 2025-04-01T06:09:05.912326+00:00 | 279 | false | # 🌲 "The Tree Kingdom and the Legend of Preorder Traversal!" ⚔️
Once upon a time, in the mystical land of Binary Trees, a wandering coder (that’s YOU! 💪) embarked on a sacred quest… to conquer the kingdom of Preorder Traversal! 👑
The Tree Guardian appeared and whispered the Golden Rule of Preorder:
`🗡️ "Root ➝ Left ➝ Right"`
$$"Wait, that’s it?" you ask.$$
*YES, brave coder. That’s it. But beware! Many have fallen into the depths of confusion.*
#### Let’s decode this spell and solve the sacred riddle of traversal! 🧙♂️
## 🔥 The Ultimate Preorder Strategy (The Holy Scrolls)
1️⃣ Visit the Root First (Respect the king! 👑)
2️⃣ Go Left (Because lefties need love too.)
3️⃣ Go Right (Right-hand warriors stand strong!)
And thus, we set forth on our glorious coding adventure! 🚀
## ⚡ The 100% Beat Solutions!
🌀 Python (The Sorcerer's Way - Recursion) 🧙♂️
```
# "First me, then left, then right!" - The Tree
def preorderTraversal(root):
return [root.val] + preorderTraversal(root.left) + preorderTraversal(root.right) if root else []
```
🔮 One-liner wizardry! No loops. No drama. Just pure recursion magic.
## ⚔️ Python (The Warrior's Way - Iterative) 🏹
```
# Stack-powered Kingdom Raid! ⚔️
def preorderTraversal(root):
if not root: return []
stack, result = [root], []
while stack:
node = stack.pop()
result.append(node.val)
if node.right: stack.append(node.right) # Right child goes in last (so left is processed first)
if node.left: stack.append(node.left) # Left child goes in first
return result
```
### 🔥 No recursion, just brute-force efficiency with a stack!
# ☕ Java Solutions (For the Code Sorcerers! 🔥)
### 🌀 Recursive Java (The Ancient Scrolls) 📜
```
import java.util.*;
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
private void preorder(TreeNode node, List<Integer> result) {
if (node == null) return;
result.add(node.val);
preorder(node.left, result);
preorder(node.right, result);
}
}
```
📜 Ancient recursion magic at work!
## ⚔️ Iterative Java (The Algorithm Warrior) 🏹
```
import java.util.*;
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
return result;
}
}
```
# **UPVOTE**

| 5 | 2 | ['Stack', 'Tree', 'Depth-First Search', 'Recursion', 'Binary Tree', 'Java', 'Python3'] | 0 |
binary-tree-preorder-traversal | Beats 100.00% using c++ without recursive method | beats-10000-using-c-without-recursive-me-1x7k | IntuitionTo perform a preorder traversal (root → left → right), we need to process the root node first, followed by the left and right subtrees. A stack can be | Saumya_Shah_09 | NORMAL | 2025-01-27T05:05:50.622048+00:00 | 2025-01-27T05:05:50.622048+00:00 | 1,038 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To perform a preorder traversal (root → left → right), we need to process the root node first, followed by the left and right subtrees. A stack can be used to simulate the recursive nature of the traversal, ensuring that nodes are processed in the correct order.
# Approach
<!-- Describe your approach to solving the problem. -->
1.Use a stack to simulate recursion.
2.Initialize the stack with the root node.
3.While the stack is not empty:
Pop the top node and add its value to the result.
Push the right child first (if it exists) so that the left child is processed first when popped from the stack.
4.Return the result vector after all nodes are processed.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n): Each node is visited exactly once, where 𝑛 is the total number of nodes in the tree.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(h): The maximum size of the stack is determined by the height ℎ of the tree. In the worst case (a skewed tree), this could be 𝑂(𝑛).
# Code
```cpp []
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> result; // Vector to store the preorder traversal
if(root == NULL)
{
return result;
}
stack<TreeNode*> st; // Stack to manage traversal
st.push(root); // Push the root node onto the stack
while(!st.empty())
{
TreeNode* current = st.top(); // Get the node at the top of the stack
st.pop(); // Remove it from the stack
result.push_back(current->val); // Add the node's value to the result
//will first insert right node so at the time of insertion the left will pop out
if(current->right)
{
st.push(current->right);
}
if(current->left)
{
st.push(current->left);
}
}
return result;
}
};
``` | 5 | 0 | ['C++'] | 0 |
binary-tree-preorder-traversal | Preorder Traversal | C solution | preorder-traversal-c-solution-by-samarth-zq29 | IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(n)
Code | samarthag01 | NORMAL | 2025-01-26T09:57:44.585249+00:00 | 2025-01-26T09:57:44.585249+00:00 | 474 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
/**
* 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 preOrder(struct TreeNode* root, int *arr, int *returnSize){
if(root!=NULL){
arr[(*returnSize)++]=root->val;
preOrder(root->left, arr, returnSize);
preOrder(root->right, arr, returnSize);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* arr=(int*)malloc(sizeof(int)*100);
*returnSize=0;
preOrder(root, arr, returnSize);
return arr;
free(arr);
}
``` | 5 | 0 | ['C'] | 0 |
binary-tree-preorder-traversal | C++ ✅ || 5 Lines Code 🎯||Beats 100 %💯 || Recursive Approach🔥 | c-5-lines-code-beats-100-recursive-appro-cul2 | Preorder Traversal of a Binary Tree 🌳✨ "Every node in DSA is a step toward mastering the tree of knowledge—keep climbing!" 🌟Intuition 🤔Preorder traversal visits | yashm01 | NORMAL | 2024-12-25T17:05:06.813011+00:00 | 2024-12-25T17:05:06.813011+00:00 | 468 | false | # Preorder Traversal of a Binary Tree 🌳
# ✨ **"Every node in DSA is a step toward mastering the tree of knowledge—keep climbing!"** 🌟

---
## Intuition 🤔
Preorder traversal visits nodes in the order: **Root ➡ Left ➡ Right**. This ensures the root is processed before its subtrees, making it ideal for tasks where the root data is prioritized.
---
## Approach 🚀
1. Use **recursion** to traverse the tree.
2. At each step:
- Process the **current node** (Root).
- Recur for the **left subtree**.
- Recur for the **right subtree**.
3. Collect values in a vector and return it.
---
## Complexity Analysis 📊
- **Time complexity:** $$O(n)$$, where $$n$$ is the number of nodes in the tree (each node is visited once).
- **Space complexity:** $$O(h)$$, where $$h$$ is the height of the tree (due to recursive stack calls).
---
## Code 💻
```cpp
class Solution {
public:
void solve(TreeNode* temp, vector<int>& ans) {
if (temp == NULL) return; // Base case
ans.push_back(temp->val); // Visit root
solve(temp->left, ans); // Traverse left subtree
solve(temp->right, ans); // Traverse right subtree
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
solve(root, ans);
return ans;
}
};
```

| 5 | 0 | ['Tree', 'Binary Tree', 'C++'] | 0 |
binary-tree-preorder-traversal | Easy Approach using C | easy-approach-using-c-by-rishi_2330-2862 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Rishi_2330 | NORMAL | 2023-11-23T06:47:36.224417+00:00 | 2023-11-23T06:47:36.224448+00:00 | 466 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * struct TreeNode *left;\n * struct TreeNode *right;\n * };\n */\n\nint* preorderTraversal(struct TreeNode* root, int* returnSize) {\n if (root == NULL) {\n *returnSize = 0;\n return NULL;\n }\n struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*));\n int stackSize = 0;\n int capacity = 1;\n int* result = (int*)malloc(sizeof(int));\n int resultSize = 0;\n while (stackSize > 0 || root != NULL) {\n while (root != NULL) {\n result = (int*)realloc(result, (resultSize + 1) * sizeof(int));\n result[resultSize++] = root->val;\n if (root->right != NULL) {\n if (stackSize >= capacity) {\n capacity *= 2;\n stack = (struct TreeNode**)realloc(stack, capacity * sizeof(struct TreeNode*));\n }\n stack[stackSize++] = root->right;\n }\n root = root->left;\n }\n if (stackSize > 0) {\n root = stack[--stackSize];\n }\n }\n free(stack);\n *returnSize = resultSize;\n return result;\n}\n\n``` | 5 | 0 | ['C'] | 0 |
binary-tree-preorder-traversal | Python 3 | Recursive and Iterative Solutions + Visual Explanation | python-3-recursive-and-iterative-solutio-sqig | Here is the visual explanation for the iterative version.\nI\'m waiting for your comments\uD83D\uDCA1\nUpvote if you like this post!\n\n\n\n\n\n\n# Iterative Ve | malkim | NORMAL | 2023-01-09T12:00:58.812510+00:00 | 2023-01-09T12:06:08.550791+00:00 | 912 | false | Here is the visual explanation for the iterative version.\nI\'m waiting for your comments\uD83D\uDCA1\n**Upvote** if you like this post!\n\n\n\n\n\n\n# Iterative Version\n```\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n self.res, stack = [], [root]\n\n while stack:\n n = stack.pop()\n if n:\n pre_list.append(n.val)\n stack.append(n.right)\n stack.append(n.left)\n\n return self.res\n```\n\n# Recursive Version\n```\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n self.res = []\n\n def preorder(curr):\n if curr:\n self.res.append(curr.val)\n preorder(curr.left)\n preorder(curr.right)\n \n preorder(root)\n return self.res\n```\n\n\n**Upvote** if you like this post! | 5 | 0 | ['Python3'] | 0 |
binary-tree-preorder-traversal | C++ Easy Solution Using Recursion and Moris traversal | c-easy-solution-using-recursion-and-mori-q34j | C++ Easy Solution Using Recursion and Moris traversal\n # Recursive Traversal\n\nclass Solution {\npublic:\n void preorder(TreeNode*&root,vector<int>&pre){\n | Conquistador17 | NORMAL | 2023-01-09T03:54:58.383714+00:00 | 2023-01-09T03:54:58.383748+00:00 | 1,073 | false | # **C++ Easy Solution Using Recursion and Moris traversal**\n* # **Recursive Traversal**\n```\nclass Solution {\npublic:\n void preorder(TreeNode*&root,vector<int>&pre){\n if(root){\n pre.push_back(root->val);\n preorder(root->left,pre);\n preorder(root->right,pre);\n }\n }\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int> pre;\n preorder(root,pre);\n return pre;\n }\n};\n```\n# ***Time Complexity : `O(N)`***\n# ***Space Complexity : `O(N)`***\n* # **Moris Traversal**\n```\nclass Solution {\npublic:\n TreeNode* rightMostFinder(TreeNode*cur,TreeNode*root){\n while(cur->right&&cur->right!=root){\n cur=cur->right;\n }\n return cur;\n }\n vector<int> preorderTraversal(TreeNode* root) {\n TreeNode*cur=root;\n vector<int>ans;\n while(cur){\n TreeNode*leftNode=cur->left;\n if(leftNode){\n TreeNode*RightMost=rightMostFinder(leftNode,cur);\n if(RightMost->right){\n RightMost->right=nullptr;\n cur=cur->right;\n }\n else{\n RightMost->right=cur;\n ans.push_back(cur->val);\n cur=cur->left;\n }\n }\n else{\n ans.push_back(cur->val);\n cur=cur->right;\n }\n }\n return ans;\n }\n};\n```\n# ***Time Complexity : `O(N)`***\n# ***Space Complexity : `O(1)`***\n# **Please Upvote if solution Helped You It really motivates me\uD83D\uDE0A**\n | 5 | 0 | ['Recursion', 'C', 'Binary Tree', 'C++'] | 0 |
binary-tree-preorder-traversal | ✅C++ || Three Solutions || Recursive , Iterative , Morris Traversal | c-three-solutions-recursive-iterative-mo-e8pz | Approach 1\nRecursive Traversal \n# Complexity\n- Time complexity : O(n)\n- Space complexity: O(n) (Function Call Stack)\n# Code\n\nclass Solution {\n void t | Brutcoder | NORMAL | 2023-01-09T03:16:01.382282+00:00 | 2023-01-09T03:16:01.382315+00:00 | 583 | false | # Approach 1\nRecursive Traversal \n# Complexity\n- Time complexity : $$O(n)$$\n- Space complexity: $$O(n)$$ (Function Call Stack)\n# Code\n```\nclass Solution {\n void traverse(TreeNode* root,vector<int>& ans)\n {\n if(root==NULL)return;\n \n ans.push_back(root->val);\n traverse(root->left,ans);\n traverse(root->right,ans);\n }\n \npublic:\n vector<int> preorderTraversal(TreeNode* root) \n {\n vector<int> ans;\n traverse(root,ans);\n return ans;\n \n }\n};\n```\n\n# Approach 2\nIterative Traversal with Stack \n# Complexity\n- Time complexity : $$O(n)$$\n- Space complexity: $$O(n)$$ (Stack space)\n# Code\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) {\n vector<int>ans;\n stack<TreeNode*>st;\n \n if(root==NULL) return ans;\n st.push(root);\n \n while(!st.empty())\n {\n TreeNode *node=st.top();\n st.pop();\n \n if(node->right!=NULL) st.push(node->right);\n if(node->left!=NULL) st.push(node->left);\n \n ans.push_back(node->val);\n }\n return ans;\n }\n};\n```\n# Approach 3\nMorris Traversal \n# Complexity\n- Time complexity : $$O(n)$$\n- Space complexity: $$O(1)$$ \n# Code\n```\nclass Solution {\npublic:\n vector<int> preorderTraversal(TreeNode* root) \n{\n vector<int>ans;\n TreeNode* curr=root;\n \n while(curr!=NULL)\n {\n if(curr->left==NULL)\n {\n ans.push_back(curr->val);\n curr=curr->right;\n }\n else\n {\n TreeNode* prev=curr->left;\n \n while(prev->right!=NULL && prev->right!=curr)\n {\n prev=prev->right;\n }\n\n if(prev->right==NULL)\n {\n prev->right=curr;\n ans.push_back(curr->val);\n curr=curr->left;\n }\n else\n {\n prev->right=NULL;\n curr=curr->right;\n }\n }\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['Stack', 'Tree', 'Depth-First Search', 'Binary Tree', 'C++'] | 0 |
binary-tree-preorder-traversal | [Rust] Iterative & recursive | 0ms | rust-iterative-recursive-0ms-by-tmtappr-zxph | Approach\nThe recursive version descends the tree through recursive calls with their state pushed on the execution stack. The traversal prefers the left branch | tmtappr | NORMAL | 2023-01-09T01:20:22.272329+00:00 | 2023-01-09T14:43:48.441074+00:00 | 643 | false | # Approach\nThe recursive version descends the tree through recursive calls with their state pushed on the execution stack. The traversal prefers the left branch over the right, and the output is built before descending either branch.\n\nThe iterative version is very similar. It also uses a stack to preserve the state of traversal. The right branch is pushed before the left, since the left branch needs to be popped before the right. The output is updated before pushing any branches.\n\nThe cloning operations in the code don\'t clone the actual tree nodes, what\'s being cloned are the smart pointers that reference them. I don\'t believe there\'s any value in avoiding cloning these.\n\n# Complexity\n- Time complexity: $$O(n)$$ Each node is visited in turn - no searching.\n- Space complexity: $$O(n + log_2(n))$$ *auxiliary* memory used. The returned vector accounts for the $$n + $$ term. For the $$log_2(n)$$ term, the memory used when pushing an execution stack frame counts in the same way the memory used when pushing an iterative stack item counts. The height of the tree determines the max number of stack items that will be piled up at any time during traversal. Assuming the tree is balanced, the height will be $$log_2(n)$$.\n\n# Code\n```rust\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\ntype NodeOpt = Option<Rc<RefCell<TreeNode>>>;\n\nimpl Solution {\n pub fn preorder_traversal(root: NodeOpt) -> Vec<i32> {\n Self::preorder_traversal_iter(root)\n //let mut result = vec![];\n //Self::preorder_traversal_recurs(root, &mut result);\n //result\n }\n fn preorder_traversal_recurs(root: NodeOpt, result: &mut Vec<i32>) {\n if let Some(pnode) = root {\n let node = pnode.borrow();\n result.push(node.val);\n Self::preorder_traversal_recurs(node.left.clone(), result);\n Self::preorder_traversal_recurs(node.right.clone(), result);\n }\n }\n fn preorder_traversal_iter(root: NodeOpt) -> Vec<i32> {\n let mut result = vec![];\n let mut stack = vec![root];\n while let Some(node_opt) = stack.pop() {\n if let Some(pnode) = node_opt {\n let node = pnode.borrow();\n result.push(node.val);\n stack.push(node.right.clone());\n stack.push(node.left.clone());\n }\n }\n result\n }\n}\n``` | 5 | 0 | ['Binary Tree', 'Rust'] | 1 |
binary-tree-preorder-traversal | Java | O(n) | 0 MS | java-on-0-ms-by-mdxabu-oyf5 | Intuition\n step 1---> add the root element in list\n step 2--->add the left element in list\n step 3--->add the right element in list\n\n# Approach\n | mdxabu | NORMAL | 2023-01-09T00:48:56.481222+00:00 | 2023-01-09T03:19:28.702229+00:00 | 908 | false | # Intuition\n step 1---> add the root element in list\n step 2--->add the left element in list\n step 3--->add the right element in list\n\n# Approach\n Using Recursion\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List<Integer> preorderTraversal(TreeNode root) {\n List<Integer> list =new ArrayList<>();\n if(root!=null){\n //root-->left-->right====>pre-order traversal\n list.add(root.val);\n list.addAll(preorderTraversal(root.left));\n list.addAll(preorderTraversal(root.right));\n return list;\n }\n // If the Root is NULL ,then return the list\n return list;\n \n }\n}\n```\n\n\n | 5 | 0 | ['Java'] | 2 |
binary-tree-preorder-traversal | 🗓️ Daily LeetCoding Challenge January, Day 9 | daily-leetcoding-challenge-january-day-9-zioz | This problem is the Daily LeetCoding Challenge for January, Day 9. Feel free to share anything related to this problem here! You can ask questions, discuss what | leetcode | OFFICIAL | 2023-01-09T00:00:15.282759+00:00 | 2023-01-09T00:00:15.282826+00:00 | 7,094 | false | This problem is the Daily LeetCoding Challenge for January, Day 9.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/binary-tree-preorder-traversal/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain this 0 approach in the official solution</summary>
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 5 | 0 | [] | 45 |
binary-tree-preorder-traversal | Beated 94.21% 😎😎 || Javascript || Simple Small Code 😇 | beated-9421-javascript-simple-small-code-ulfw | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sikkasakshi2 | NORMAL | 2022-12-01T18:54:24.089779+00:00 | 2022-12-01T18:54:24.089826+00:00 | 930 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nvar preorderTraversal = function (root) {\n let arr = []\n const getVal = (root) => {\n if(!root)\n return \n arr.push(root.val)\n getVal(root.left)\n getVal(root.right)\n }\n getVal(root)\n return arr\n};\n``` | 5 | 0 | ['Recursion', 'JavaScript'] | 4 |
binary-tree-preorder-traversal | Preorder | preorder-by-louis-chery-xrbv | \nclass Solution {\npublic:\n vector<int> a;\n void preorder(TreeNode* root)\n {\n if(root)\n {\n a.push_back(root->val);\n | louis-chery | NORMAL | 2022-11-01T03:25:20.027431+00:00 | 2022-11-01T03:25:20.027477+00:00 | 712 | false | ```\nclass Solution {\npublic:\n vector<int> a;\n void preorder(TreeNode* root)\n {\n if(root)\n {\n a.push_back(root->val);\n preorder(root->left);\n preorder(root->right);\n }\n }\n vector<int> preorderTraversal(TreeNode* root) {\n preorder(root);\n return a;\n }\n};\n``` | 5 | 0 | [] | 0 |
construct-the-minimum-bitwise-array-ii | Efficient bitwise O(NlogK) | efficient-bitwise-onlogk-by-david1121-0vb5 | Intuition\nI solved this problem by noticing a pattern in the given examples:\n\n\nInput | Answer | Input | Answer\n-------------------------------\n2 | david1121 | NORMAL | 2024-10-12T16:00:54.065088+00:00 | 2024-10-17T02:49:28.201261+00:00 | 2,882 | false | # Intuition\nI solved this problem by noticing a pattern in the given examples:\n\n```\nInput | Answer | Input | Answer\n-------------------------------\n2 -1 10\n3 1 11 1\n5 4 101 100\n7 3 111 11\n11 9 1011 1001\n13 12 1101 1100\n31 15 11111 1111\n```\n\n- If the binary ends in 01 (like 5 and 13), then the answer is to just subtract 1.\n- If the binary consists of all 1s (like 7 and 31), the answer is to remove the leftmost 1.\n- 11 is the only one that doesn\'t fit into the above. I noticed that the answer involves removing that 2nd 1 from the right (1011 -> 1001). And in general, the approach is to remove the leftmost 1 of the longest chain of 1s starting from the right. So for 11, we remove the 2nd 1 to make it 1001, because if we add a 1, it can be ORed back to 11:\n```\n 1001\nOR 1010\n ----\n 1011\n```\n**This holds true for all numbers** except for 2.\n\nSome more examples:\n\n`1111111` (127) would become `0111111` | `1000000` (63 | 64).\n```\n 0111111\nOR 1000000\n -------\n 1111111\n```\n\n`11101111` (239) would become `11100111` | `11101000` (231 | 232).\n```\n 11100111\nOR 11101000\n --------\n 11101111\n```\n\n`1110001` (113) would become `1110000` | `1110001` (112 | 113).\n```\n 1110000\nOR 1110001\n -------\n 1110001\n```\n\n# Approach\nIf the number is 2, add -1 to the answer array. Else, start checking the bits from the right. Move left everytime there is a 1. When the first 0 is found, remove the 1 to the right. This minimizes the number as much as possible.\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n\n for num in nums:\n if num == 2:\n ans.append(-1)\n continue\n\n num_copy = num\n count = 0\n\n # Count consecutive 1s from the right\n while num & 1 == 1:\n count += 1\n num >>= 1\n \n # [count]th bit is the position of the last 1, like 100111 (count = 3)\n # Subtract the bit ^\n ans.append(num_copy - 2 ** (count-1))\n \n return ans\n```\n``` java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] ans = new int[nums.size()];\n\n for (int i = 0; i < nums.size(); i++) {\n int num = nums.get(i);\n\n if (num == 2) {\n ans[i] = -1;\n continue;\n }\n\n int numCopy = num;\n int count = 0;\n\n // Count consecutive 1s from the right\n while ((num & 1) == 1) {\n count++;\n num >>= 1;\n }\n\n // [count]th bit is the position of the last 1, like 100111 (count = 3)\n // Subtract the bit ^\n ans[i] = numCopy - (1 << (count - 1));\n }\n\n return ans;\n }\n}\n```\n\n``` cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans(nums.size());\n\n for (int i = 0; i < nums.size(); i++) {\n int num = nums[i];\n\n if (num == 2) {\n ans[i] = -1;\n continue;\n }\n\n int numCopy = num;\n int count = 0;\n\n // Count consecutive 1s from the right\n while ((num & 1) == 1) {\n count++;\n num >>= 1;\n }\n\n // [count]th bit is the position of the last 1, like 100111 (count = 3)\n // Subtract the bit ^\n ans[i] = numCopy - (1 << (count - 1));\n }\n\n return ans;\n }\n};\n\n```\n``` javascript []\nvar minBitwiseArray = function(nums) {\n let ans = new Array(nums.length);\n\n for (let i = 0; i < nums.length; i++) {\n let num = nums[i];\n\n if (num === 2) {\n ans[i] = -1;\n continue;\n }\n\n let numCopy = num;\n let count = 0;\n\n // Count consecutive 1s from the right\n while ((num & 1) === 1) {\n count++;\n num >>= 1;\n }\n\n // [count]th bit is the position of the last 1, like 100111 (count = 3)\n // Subtract the bit ^\n ans[i] = numCopy - (1 << (count - 1));\n }\n\n return ans;\n};\n\n```\n\n# Complexity\n- Time complexity: $$O(NlogK)$$ where K is the largest number in `nums`\n- Auxiliary space complexity: $$O(1)$$ | 55 | 7 | ['Bit Manipulation', 'C++', 'Java', 'Python3', 'JavaScript'] | 5 |
construct-the-minimum-bitwise-array-ii | [Java/C++/Python] Low Bit, O(n) | javacpython-low-bit-on-by-lee215-6dla | Intuition\nans[i] OR (ans[i] + 1) == nums[i]\nans[i] and ans[i] + 1 are one odd and one even.\nnums[i] is an odd.\n\n\n# Explanation\n..0111 || (..0111 + 1) = | lee215 | NORMAL | 2024-10-12T17:30:12.657926+00:00 | 2024-10-18T02:46:49.635106+00:00 | 830 | false | # **Intuition**\n`ans[i] OR (ans[i] + 1) == nums[i]`\n`ans[i]` and `ans[i] + 1` are one odd and one even.\n`nums[i]` is an odd.\n<br>\n\n# **Explanation**\n`..0111 || (..0111 + 1) = ..1111`\nThe effect is that change the rightmost 0 to 1.\n\nFor each `a` in array `A`,\nfind the rightmost 0,\nand set the next bit from 1 to 0.\n\n`a + 1` will filp the 1-suffix to 0-suffix,\nand flip the rightmost 0 to 1.\n`a & -a` is a trick to get the rightmost 1.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(n)` for result\n<br>\n\n**Java**\n```java\n public int[] minBitwiseArray(List<Integer> A) {\n int n = A.size(), res[] = new int[n];\n for (int i = 0; i < n; i++) {\n int a = A.get(i);\n if (A.get(i) % 2 == 0) {\n res[i] = -1;\n } else {\n res[i] = a - ((a + 1) & (-a - 1)) / 2;\n }\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n vector<int> minBitwiseArray(vector<int>& A) {\n vector<int> res;\n for (int a : A) {\n if (a % 2 == 0) {\n res.push_back(-1);\n } else {\n res.push_back(a - ((a + 1) & (-a - 1)) / 2);\n }\n }\n return res;\n }\n```\n\n**Python**\n```py\n def minBitwiseArray(self, A: List[int]) -> List[int]:\n res = []\n for a in A:\n if a % 2 == 0:\n res.append(-1)\n else:\n res.append(a - ((a + 1) & (-a - 1)) // 2)\n return res\n```\n | 21 | 5 | ['C', 'Python', 'Java'] | 3 |
construct-the-minimum-bitwise-array-ii | Explained - Bit wise manipulation || Very simple and easy understand | explained-bit-wise-manipulation-very-sim-68ip | \n# Intuition \n- By analysing few cases I observed following:\n - as all are prime except 2, all numbers are odd ( so the last bit is set)\n - as all numbers | kreakEmp | NORMAL | 2024-10-12T16:02:07.162480+00:00 | 2024-10-12T16:02:07.162505+00:00 | 1,850 | false | \n# Intuition \n- By analysing few cases I observed following:\n - as all are prime except 2, all numbers are odd ( so the last bit is set)\n - as all numbers are odd => trivial ans is n-1. Where n-1 one has last bit set to zero and (n-1) | n will be always eqaul to n\n - Now we need to optimise further to find a smaller number that satisfy given condition\n - if all bits are not set then the highest bit must be set in the answer as well.( the answer must be number whose largest bit is same as that of given number)\n\n- Finally concluded with the following two cases :\n 1. when all bits are one (that is the number is in the form n^2 -1 ) => then answer will be n/2\n 2. when all bits are not one => \n - then in the answer the highest bit must be set( Need to find the largest number less than current number which is a power of 2 and add this value to answer)\n - then set the highest bit to zero. ( subtract largest number less than current number which is smaller than 2)\n Other way of thinking this is => \n \nLets take an example of n = 13 ( 1101) and initialize ans with 0\nNow n is not a number whose all bits are set, so we remove the highest bit and the same is added to ans temporary variable.\nor you can think up lik find the largest number which is power of 2 and less than n (that is 8 here ) and subtract this from the number ( this will set the higest bit zero) and add this number to the ans as well.\nSo now n = 13 - 8 = 5 and ans = 0 + 8 = 8\n\nIn next iteration n = 5 is again not in the form which has all bits set, so we repeat above steps\nfind the largest power of 2 which is smaller than n = 5 that is 4\nNow subtract 4 from n and add it to the ans => n = 5 - 4 = 1 and ans = 8 + 4 = 12\n\nIn next iteration we find that n = 1 is in the form where all the bits are set. So we add n/2 to ans and set n to zero\nn = 0 and ans = 12 + 1/2 = 12\n \nHence here our answer is 12\n\n# Approach \n- Iterate over each number in the nums\n- if n is equal to 2 which is a even number and we will consider a special case here. So return the answer as -1\n- if not equal to 2 then do the following steps:\n - initialize temp answer sum to zero and copy value of n to a temp var t\n - now if t is greater than 0 then repeat :\n - if it is in the form where all bits are set(or we can check if n+1 is a power of 2 or not) then sum qill be equal to t/2 and set t to zero\n - if all bits are not set then find the largest number which is power of 2 and less than t. Add the number to sum and subtract it from t\n\n# Code\n```\nclass Solution {\npublic:\n bool isPowerOfTwo(int n) {\n return ((n & (n - 1)) == 0);\n }\n \n int largestPowerOfTwoLessThan(int n) {\n if (n <= 1) return 0;\n int exponent = floor(log2(n));\n return 1 << exponent; // Equivalent to pow(2, exponent)\n }\n \n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ans;\n for(auto n: nums){\n if(n == 2) ans.push_back(-1);\n else{\n int t = n, sum = 0;\n while(t > 0){\n if(isPowerOfTwo(t+1)){\n sum += t/2;\n t = 0;\n }else{\n int d = largestPowerOfTwoLessThan(t);\n sum += d;\n t -= d;\n }\n }\n ans.push_back(sum);\n }\n }\n return ans;\n }\n};\n```\n\n---\n\n\n<b>Here is an article of my interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n--- | 17 | 6 | ['C++'] | 4 |
construct-the-minimum-bitwise-array-ii | Python3 || 11 lines, just odd numbers || T/S: 98% / 64% | python3-11-lines-just-odd-numbers-ts-98-07gpf | Here\'s the intuition:\nThe prime number condition is a red herring. The real condition is the elements of nums are odd integers (excepting of course, 2). Odd n | Spaulding_ | NORMAL | 2024-10-12T17:42:28.808194+00:00 | 2024-10-16T21:22:03.877971+00:00 | 232 | false | Here\'s the intuition:\nThe *prime number* condition is a *red herring*. The real condition is the elements of `nums` are odd integers (excepting of course, 2). Odd numbers are either 4 mod 1 or 4 mod 3. The *4 mod 1* case becomes trivial after analyzing some examples. The *4 mod 3* case requires a bit more investigation, but does have an inuitive answer as well.\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums):\n\n def helper(num):\n\n if num %4 == 1: # <-- 4 mod 1 case\n return num - 1 \n\n if num %4 == 3: # <-- 4 mod 3 case\n tmp = num\n for i in range(num.bit_length()):\n tmp //= 2\n if not tmp%2: break\n \n return num - (1<<i) \n\n return -1 # <-- just for num = 2\n\n\n return map(helper,nums)\n```\n```cpp []\nclass Solution {\npublic:\n std::vector<int> minBitwiseArray(const std::vector<int>& nums) {\n std::vector<int> result;\n \n for (int num : nums) {\n result.push_back(helper(num));\n }\n \n return result;\n }\n \nprivate:\n int helper(int num) {\n if (num % 4 == 1) { // Case when num % 4 == 1\n return num - 1;\n }\n \n if (num % 4 == 3) { // Case when num % 4 == 3\n int tmp = num;\n for (int i = 0; i < (int)log2(num) + 1; ++i) {\n tmp /= 2;\n if (tmp % 2 == 0) {\n return num - (1 << i);\n }\n }\n }\n\n return -1; // Special case for num == 2\n }\n};\n\n```\n```java []\n\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n List<Integer> result = new ArrayList<>();\n for (int num : nums) {\n result.add(helper(num));}\n\n int[] arrayResult = new int[result.size()];\n for (int i = 0; i < result.size(); i++) {\n arrayResult[i] = result.get(i);}\n \n return arrayResult;}\n\n private int helper(int num) {\n if (num % 4 == 1) { // 4 mod 1 case\n return num - 1;\n }\n if (num % 4 == 3) { // 4 mod 3 case\n int tmp = num;\n int i = 0;\n while (tmp > 0) {\n tmp /= 2;\n if (tmp % 2 == 0) break;\n i++;}\n\n return num - (1 << i);}\n return -1; // just for num = 2\n }\n}\n```\n[https://leetcode.com/problems/construct-the-minimum-bitwise-array-ii/submissions/1420215826/](https://leetcode.com/problems/construct-the-minimum-bitwise-array-ii/submissions/1420215826/)\n\n\nI could be wrong, but I think that time complexity is *O*(*NB*) and space complexity is *O*(*N*), in which *N* ~ `len(nums)` and *B* ~ average bit length the elements in `nums`. | 12 | 2 | ['C++', 'Java', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | Bit Before Leftmost Zero | bit-before-leftmost-zero-by-votrubac-offw | There is no answer for an even number. \n\nFor an odd number n, there is always an answer: n - 1 (since (n - 1) | n == n).\n\nHowever, there could be other answ | votrubac | NORMAL | 2024-10-13T02:01:13.434889+00:00 | 2024-10-13T02:11:48.811544+00:00 | 217 | false | There is no answer for an even number. \n\nFor an odd number `n`, there is always an answer: `n - 1` (since `(n - 1) | n == n`).\n\nHowever, there could be other answers, such as `n - 2`, `n - 4`, `n - 8` and so on.\n\nTo find the minimum answer, let\'s look at example `111` (`0b1101111`):\n- `0b1101111 - 0b0001`; `0b1101110 | 0b1101111 == 0b1101111`\n- `0b1101111 - 0b0010`; `0b1101101 | 0b1101110 == 0b1101111`\n- `0b1101111 - 0b0100`, `0b1101011 | 0b1101100 == 0b1101111`\n- `0b1101111 - 0b1000`, `0b1100111 | 0b1101000 == 0b1101111`\n\t- This will not work for `0b10000` as it will flip a zero bit, so the OR result won\'t be equal to `n`.\n\nAs you can see, the smallest answer can be achieved by removing a bit before the leftmost zero.\n\n**C++**\n```cpp\nvector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> res;\n for (int n : nums) {\n if (n % 2) {\n int bit = 1;\n for (int x = n; x & 2; x >>= 1)\n bit <<= 1;\n res.push_back(n ^ bit); \n }\n else\n res.push_back(-1);\n }\n return res;\n}\n``` | 7 | 2 | [] | 1 |
construct-the-minimum-bitwise-array-ii | [Java/Python 3] Bit Manipulation w/ brief explanation and analysis. | javapython-3-bit-manipulation-w-brief-ex-1que | Intuition:\n1. ans[i] | (ans[i] + 1) must be odd, therefore there is no way to find an ans[i] such that ans[i] | (ans[i] + 1) = 2; Hence, return -1 for 2;\n2. B | rock | NORMAL | 2024-10-12T16:03:34.060938+00:00 | 2024-10-13T17:55:43.590026+00:00 | 437 | false | **Intuition:**\n1. `ans[i] | (ans[i] + 1)` must be odd, therefore there is no way to find an `ans[i]` such that `ans[i] | (ans[i] + 1) = 2`; Hence, return `-1` for `2`;\n2. By observation, for any given binary number `0...1...0...11...1`, only the ending `11....1` part can be minimized to `01...1` such that `01...1 + 1 = 10...0`, hence `01...1 | 10...0 = 11...1`. That is, **remove the one bit just right of right-most zero bit**:\n\n`01...1`\n`10...0`\n\n--\n`11...1`\n\nTherefore, we can isolate this kind of ending to minimize the result.\n\n```java\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] ans = new int[nums.size()];\n for (int i = 0; i < nums.size(); ++i) {\n ans[i] = getVal(nums.get(i));\n }\n return ans;\n }\n private int getVal(int x) {\n if (x == 2) {\n return -1;\n } \n int lowestOneBit = Integer.lowestOneBit(x + 1);\n x -= lowestOneBit >> 1;\n return x;\n }\n```\n\n```python\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n for x in nums:\n if x == 2:\n ans.append(-1)\n else:\n lowest_one_bit = (x + 1) & -(x + 1)\n x -= lowest_one_bit >> 1\n ans.append(x) \n return ans\n```\n\nor\n\n```python\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n for x in nums:\n if x == 2:\n ans.append(-1)\n else:\n y = 0\n for i in range(x.bit_length() - 1, -1, -1):\n if (x + 1).bit_count() == 1:\n y += x // 2\n break\n if (x & (1 << i)) > 0:\n y += 1 << i\n x -= 1 << i\n ans.append(y) \n return ans\n```\n\nMake the above codes shorter:\n```java\n public int[] minBitwiseArray(List<Integer> nums) {\n return nums.stream().mapToInt(this::getVal).toArray();\n }\n private int getVal(int x) {\n return x == 2 ? -1 : x - (Integer.lowestOneBit(x + 1) >> 1);\n }\n```\n\n```python\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n return [-1 if x == 2 else x - (((y := x + 1) & -y) >> 1) for x in nums]\n```\n\n**Analysis:**\n\nTime: `O(nlog(max))`, space: `O(1)`- excluding output space, where `n = nums.length, max = max(nums)`.\n | 7 | 0 | ['Bit Manipulation', 'Java', 'Python3'] | 3 |
construct-the-minimum-bitwise-array-ii | 💡 [EASY] INTUITION & EXPLANATION | easy-intuition-explanation-by-ramitgangw-83pz | \n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n \n\n\n# \u2B50 Problem Overview\nIn this problem, you are tasked with constructing an array ans | ramitgangwar | NORMAL | 2024-10-12T16:08:15.687979+00:00 | 2024-10-12T16:08:15.688003+00:00 | 372 | false | <div align="center">\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n</div>\n\n***\n# \u2B50 Problem Overview\nIn this problem, you are tasked with constructing an array `ans` from an array `nums` of prime integers. For each index `i`, the relationship that must hold is `ans[i] | (ans[i] + 1) = nums[i]`. The challenge is to minimize each value of `ans[i]` while ensuring the condition is satisfied.\n\n# \u2B50 Differences from the First Part of the Question\nThe first part of the question allows for a more straightforward search for `ans[i]`, since there are fewer constraints on the values in `nums`. However, in this second part:\n\n- **Tight Constraints**: \n - The constraints are stricter, with `nums[i]` being guaranteed as a prime number. Prime numbers have specific properties in terms of their binary representation, which restricts the possible values for `ans[i]`.\n - Additionally, each number in `nums` can be as large as 10^9, meaning that naive brute-force searching would be inefficient.\n\n# \u2B50 Intuition\nGiven the properties of prime numbers, any prime number `p` can be expressed in binary, and the task requires finding an `ans[i]` such that the bitwise OR operation with its successor produces the prime number itself. This requires a careful examination of each bit in the prime.\n\n# \u2B50 Approach\n1. **Initialization**: \n - We start by creating an output array `ans`, where we will store our results.\n\n2. **Iterate Through Each Prime Number**: \n - For each number in `nums`, we initialize `minimalValue` to a very large number (Integer.MAX_VALUE) to ensure that any valid candidate found will be smaller.\n\n3. **Bit Position Examination**: \n - Unlike the first part of the problem, which could iterate through all possible values below the prime, we focus specifically on the bit positions of the current prime number. \n - We only check for bits that are set in `num`, because unsetting a bit in a prime should ideally lead us to the next smaller candidate that still satisfies the condition.\n\n4. **Finding Candidates**: \n - When we unset a bit in `num`, we form a candidate. The candidate must be checked to see if it meets the requirement: `(candidate | (candidate + 1)) == num`.\n - The search for candidates is limited to 30 iterations because we are working within the constraint of 10^9, which fits within 30 bits.\n\n5. **Store Valid Results**: \n - If a valid candidate is found for a particular `num`, we update `minimalValue`. If no valid candidate is found after checking all relevant bit positions, we set `ans[i]` to -1.\n \n6. **Return the Result**: \n - Finally, we return the constructed `ans` array containing the minimal values or -1 where appropriate.\n\n# \u2B50 Code\n```java []\nclass Solution { \n public int[] minBitwiseArray(List<Integer> arr) {\n int[] ans = new int[arr.size()];\n int index = 0;\n\n for (int num : arr) {\n int minimalValue = Integer.MAX_VALUE;\n boolean isValid = false;\n\n for (int bitPosition = 0; bitPosition <= 30; bitPosition++) {\n if ((num & (1 << bitPosition)) != 0) {\n int candidate = num & ~(1 << bitPosition);\n if (candidate >= 0 && (candidate | (candidate + 1)) == num) {\n if (candidate < minimalValue) {\n minimalValue = candidate;\n isValid = true;\n }\n }\n }\n }\n ans[index++] = isValid ? minimalValue : -1;\n }\n \n return ans;\n }\n}\n``` | 6 | 0 | ['Bit Manipulation', 'Bitmask', 'Java'] | 1 |
construct-the-minimum-bitwise-array-ii | [Python3] Brute-Force -> Greedy - Detailed Solution | python3-brute-force-greedy-detailed-solu-asxc | Intuition\n Describe your first thoughts on how to solve this problem. \n- Using pen and draw some examples and recognized the pattern\n\n\nInput | Answer | Inp | dolong2110 | NORMAL | 2024-10-12T16:53:16.082646+00:00 | 2024-10-12T16:53:16.082673+00:00 | 143 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Using pen and draw some examples and recognized the pattern\n\n```\nInput | Answer | Input | Answer\n-------------------------------\n2 -1 10\n3 1 11 1\n5 4 101 100\n7 3 111 11\n11 9 1011 1001\n13 12 1101 1100\n17 16 10001 10000\n19 17 10011 10001\n31 15 11111 1111\n```\n\n- From the expamples I drawn It is recognized that the `answer` is the original number removing the most-left `1` bit of the continous 1 chain from starting from the right.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**`helper(num)` function:**\n\n**1. Base Case:**\n\n- `if num == 2: return -1`\n - This handles a specific case where the input number is 2. It directly returns -1 for this case. It seems like a special condition for this particular problem.\n\n**2. Binary Conversion:**\n\n- `bin_arr = [0] + list(map(int, bin(num)[2:]))`\n - `bin(num)` converts the integer num to its binary representation as a string (e.g., `bin(5)` returns `"0b101"`).\n- `[2:]` slices the string to remove the "0b" prefix.\n- `map(int, ...)` converts each character (\'1\' or \'0\') in the string to an integer.\n- `list(...)` creates a list of these integers.\n- `[0] + ...` adds a leading 0 to the list. This is likely done to handle potential edge cases during the bit manipulation later.\n\n**3. Bit Manipulation:**\n\n- `for i in range(len(bin_arr) - 1, -1, -1):`\n - This loop iterates through the `bin_arr` in reverse order (from the least significant bit to the most significant bit).\n - `if bin_arr[i] == 0:`\n - If a 0 bit is found:\n - `bin_arr[i + 1] = 0` : The next higher bit (to the left) is set to 0.\n - `break`: The loop terminates after this change.\n - This part seems to be designed to modify the binary representation in a specific way. It essentially finds the rightmost \'1\' bit and sets the bit to its left to \'0\'.\n \n**4. Decimal Conversion:**\n\n- `res = power = 0`\n - Initializes `res` (to store the result) and `power` (to keep track of the power of 2) to 0.\n- `for i in range(len(bin_arr) - 1, -1, -1):`\n - This loop iterates through the modified `bin_arr` in reverse order.\n - `res += bin_arr[i] * (2 ** power)`\n - This calculates the decimal value of each bit and adds it to `res`.\n - `res + bin_arr[i]`\n - `power += 1`\n - Increments the `power` for the next bit.\n- `return res`: Returns the calculated decimal value.\n\n**`minBitwiseArray(nums)` function:**\n\n- `return [helper(num) for num in nums]`\n - This uses list comprehension to apply the `helper` function to each number in the input list `nums` and returns a new list with the transformed values.\n\n**Overall, the code seems to be designed to:**\n\n1. Convert each number in the input list to its binary representation.\n2. Modify the binary representation by finding the rightmost \'1\' and setting the bit to its left to \'0\'.\n3. Convert the modified binary representation back to decimal.\n\n# Code\n##### 1. Brute-Force\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n def helper(num: int) -> int:\n for new_num in range(num):\n if new_num | (new_num + 1) == num: return new_num\n return -1\n \n return [helper(num) for num in nums]\n```\n\n- Time complexity: $$O(N * M)$$ with `N` is the number of number in `nums` and `M` is the number in `nums`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n##### 2. Greedy\n```\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n def helper(num: int) -> int:\n if num == 2: return -1\n bin_arr = [0] + list(map(int, bin(num)[2:]))\n for i in range(len(bin_arr) - 1, -1, -1):\n if bin_arr[i] == 0:\n bin_arr[i + 1] = 0\n break\n res = power = 0\n for i in range(len(bin_arr) - 1, -1, -1):\n res += bin_arr[i] * (2 ** power)\n res + bin_arr[i]\n power += 1\n return res\n \n return [helper(num) for num in nums]\n```\n- Time complexity: $$O(N * 32)$$ with `N` is the number of number in `nums` and `M` is the number in `nums`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 5 | 1 | ['Greedy', 'Bit Manipulation', 'Python3'] | 1 |
construct-the-minimum-bitwise-array-ii | Simple power of 2 Solution Java(O(n*32)) | simple-power-of-2-solution-javaon32-by-r-wvo6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n# Complexity\n- Time co | rajnarayansharma110 | NORMAL | 2024-10-12T17:56:40.477796+00:00 | 2024-10-12T17:56:40.477818+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Complexity\n- Time complexity:O(n*32)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int[] res=new int[nums.size()];\n int k=0;\n for(int x:nums){\n if(x==2){\n res[k++]=-1;\n continue;\n }\n int best=x;\n for(int i=0;i<32;i++){\n if(((x-(1<<i))|((x-(1<<i))+1))==x){\n best=Math.min(x-(1<<i),best);\n }\n }\n res[k++]=best;\n }\n return res;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Solution In Java ✅ | 9 Lines | Beats 100% ✅✅✅ In Both Space And Time Complexity!!!! | easy-solution-in-java-9-lines-beats-100-l8d1o | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires generating an array based on bitwise operations. For each element | somgester13 | NORMAL | 2024-10-14T17:04:57.330597+00:00 | 2024-10-14T17:04:57.330622+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires generating an array based on bitwise operations. For each element in the input list, the task is to find the smallest number j such that modifying its bits in a specific way results in the original value. To do this, bitwise operations are useful for checking and toggling bits.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initial Setup:** Create an array ans initialized with -1 values, as placeholders for values that are either invalid or don\'t meet the condition.\n2. **Iterate through the input list nums:**\n- For each value val in nums, we check if it is equal to 2. If so, skip processing as 2 doesn\u2019t need further evaluation.\n- Otherwise, iterate through the bits of val.\n3. **Bitwise Check and Toggle:**\n- Use a bitmask (1 << j) to check the jth bit of val. If it\'s 0, this is where we can potentially toggle the bits to form a smaller number.\n- When a valid number is found (using XOR to flip the bits), it is stored in the ans array.\n4. **Return the result:** After iterating through all elements, return the modified ans array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(nlog(val))\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int [] ans = new int[nums.size()];\n Arrays.fill(ans, -1);\n for (int i = 0; i < nums.size(); i++) \n {\n int val = nums.get(i);\n if(val == 2) continue;\n for (int j = 0; j < val; j++) \n {\n // if ((j | (j + 1)) == val) \n // {\n // ans[i] = j; \n // break;\n // }\n\n if((val & (1 << j)) == 0)\n {\n ans[i] = val ^ (1 << (j - 1));\n break;\n }\n }\n }\n return ans;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Solution | Explained with Example walk through | Simple logic | easy-solution-explained-with-example-wal-4edp | Approach\n- Loop through the input list of numbers:\nFor each number in the list nums, we call the function minval(num) to find the smallest possible i for that | Guna01 | NORMAL | 2024-10-12T16:28:27.316238+00:00 | 2024-10-12T17:28:52.638551+00:00 | 82 | false | # Approach\n- Loop through the input list of numbers:\nFor each number in the list nums, we call the function minval(num) to find the smallest possible i for that number.\n\n- In the minval function:\nWe iterate through each bit of num from the most significant bit (MSB) to the least significant bit (LSB).\nFor each bit, we flip that bit (change 1 to 0 or 0 to 1) and check if the modified number satisfies the condition (i\u2223(i+1))==num.\nIf we find such a number i, we return it.\nIf no such number is found after trying all bits, return -1.\n\n# Example\nNumber: 11\nBinary of 11: 1011.\n\nWe will now try to flip each bit of 11 and check if the result satisfies the condition.\n\nFlip the 3rd bit (MSB):\nFlip 1011 \u2192 0011 (3 in decimal).\nCheck: \n(3\u2223(3+1))==11?\n3\u22234=7, which is not equal to 11. So, this doesn\'t work.\n\nFlip the 2nd bit:\nFlip 1011 \u2192 1111 (15 in decimal).\nCheck: \n(15\u2223(15+1))==11?\n15\u222316=31, which is not equal to 11. So, this doesn\'t work.\n\nFlip the 1st bit:\nFlip 1011 \u2192 1001 (9 in decimal).\nCheck: \n(9\u2223(9+1))==11?\n9\u222310=11, which is equal to 11! This works.\n\nSo, the smallest number for 11 is 9.\n\n\nFinal Result:\nFor the input list [11, 13, 31], the smallest values are:\n\n11 \u2192 9\n\nSimilarly all for all other numbers in array.\n\n# Complexity\n- Time complexity: $$O(n)$$\nwhere n is the number of bits in the number\n\n### Upvote if this solution is good \u2B06\uFE0F\n\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int n = nums.size();\n int[] ans = new int[n];\n for (int j = 0; j < n; j++) {\n int num = nums.get(j);\n ans[j] = minval(num);\n }\n\n return ans;\n }\n\n private int minval(int num) {\n int og = num;\n int len = Integer.SIZE - Integer.numberOfLeadingZeros(num);\n \n for (int i = len - 1; i >= 0; i--) {\n int changed = num ^ (1 << i);\n if ((changed | (changed + 1)) == og) {\n return changed; \n }\n }\n\n return -1; \n }\n\n \n}\n\n``` | 3 | 0 | ['Bit Manipulation', 'Bitmask', 'Java'] | 0 |
construct-the-minimum-bitwise-array-ii | Flip the First 1 Before the Leftmost 0 | flip-the-first-1-before-the-leftmost-0-b-ddpz | IntuitionTo minimize the array element bitwise, flip the leftmost '1' bit before the first '0' in its binary representation. Special cases include numbers ≤2, w | Saurav_kumar_10 | NORMAL | 2024-12-29T18:33:58.395713+00:00 | 2024-12-29T18:33:58.395713+00:00 | 44 | false | # Intuition
To minimize the array element bitwise, flip the leftmost '1' bit before the first '0' in its binary representation. Special cases include numbers ≤2, which cannot be minimized further.
# Approach
1. **Handle Edge Case**: If `nums[i] <= 2`, push `-1` as it's already minimal.
2. **Iterate and Identify**: For each number, find the leftmost `1` bit before the first `0`.
3. **Bitwise Operation**: Flip this bit using `nums[i] & (~(1 << j))`.
4. **Store Result**: Push the result into the output vector.
# Complexity
- **Time Complexity**: $$O(N)$$, where $$N$$ is the size of the input array.
- **Space Complexity**: $$O(1)$$ additional space, excluding the result vector.
# Code
```cpp
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector <int> ans;
for(int i=0;i<nums.size();i++){
//leftmost 0 se pehle wala 1 ko flip krna h
//only 2 is the even prime number
// so no need to deal with 4(100),8(1000),16(10000),etc.
//for 3(11 take it as 011) -> push(001)
if(nums[i]<=2) ans.push_back(-1);
else{
int num=nums[i];
int j=-1;
while((num&1)| 0 == 1){
j++;
num=num>>1;
}
ans.push_back(nums[i] & (~(1<<j)));
}
}
return ans;
}
};
``` | 2 | 0 | ['Array', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ one line solution | Explained arithmetically | c-one-line-solution-explained-arithmetic-2oi0 | Deduction\nIt is impossible to find an answer for even numbers since the bitwise or of two consecutive number is always odd \ni.e.:\n \u274C $6 (0b110)$\n> | alecapiani | NORMAL | 2024-11-09T13:06:24.136833+00:00 | 2024-11-10T16:51:25.512607+00:00 | 62 | false | # Deduction\nIt is impossible to find an answer for even numbers since the bitwise or of two consecutive number is always odd \ni.e.:\n \u274C $6 (0b110)$\n> $4 |_{or} 5 = 5$\n> $5 |_{or} 6 = 7$\n> $6 |_{or} 7 = 7$\n \n \u274C $2 (0b10)$ \n> $0 |_{or} 1 = 1$\n> $1 |_{or} 2 = 3$\n\nBut since all primes expect 2 are odd we just need to exclude 2 from the algorithm.\n\n---\n\nIf we observe any number ```a``` formed by a sequence of **consecutive** set bit\n$a=2^0+2^1+\\dots+2^{n-1}=\\sum_{i=0}^{n-1} 2^i = 2^n - 1$,\nwe note that the minimum value ```b``` for which $a=b|_{or}(b+1)$\nis the number we obtain by clearing the most significative bit from ```a``` ($2^{n-1}$),\n$b=a-2^{n-1}=2^0+2^1+\\dots+2^{n-2}=\\sum_{i=0}^{n-2} 2^i = 2^{n-1} - 1$,\nsince $b+1 = 2^{n-1}$ represents the bit we removed from ```a``` to obtain ```b```\n$b|_{or}(b+1) = (2^{n-1}-1)|_{or}2^{n-1} = 2^{n-1} + 2^{n-1} - 1 = 2^{n}-1 = a$\ni.e. \n> for $n=3 $\n> $ a = 2^n-1 = 7 (0b\\underline111)$\n> $b = 2^{n-1}-1 = 3 (0b\\underline011)$\n> $b|_{or}(b+1) = 0b011 |_{or} 0b100 = 7 (0b111) = a$\n\nThis process can be extended to any odd number,\nsince odd numbers can be decomposed into their less significative consecutive bit sequence plus a constant.\n$a = 2*k+1 = \\alpha*2^{n+1} + \\sum_{i=0}^{n-1} 2^i = \\alpha*2^{n+1} + 2^{n}-1 = \\beta + 2^n-1$ for some $\\alpha, n$,\nthen\n$b = \\beta + \\sum_{i=0}^{n-2} 2^i = \\beta + 2^{n-1}-1$\n$b+1 = \\beta + 2^{n-1}$\n$b|_{or}(b+1) = (\\beta + 2^{n-1}-1) |_{or} (\\beta + 2^{n-1}) = (\\beta|\\beta) + [(2^{n-1}-1) |_{or} 2^{n-1}] = \\beta +2^n-1 = a$\ni.e.\n$ a = 13 = 8 + 4 + \\underline{1}$\n> $\\beta = 8 + 4$, $n = 1 $\n> then $ b = \\beta + 2^{n-1}-1 = (8+4) + 2^{1-1}-1 = 12$\n> $12|_{or}13 = 13 $\n\n$ a = 11 = 8 + \\underline{2 + 1}$\n> $\\beta = 8,$ $n = 2$\n> then $ b = \\beta + 2^{n-1}-1 = 8 + 2^{2-1}-1 = 9$\n> $9|_{or}10 = 11 $\n---\n\nIt follows that for each odd numbers the answer is to set to 0 the bit at the previous index of the lowest clear bit\ni.e.: \n\u2714\uFE0F $13 (0b1101)$\n> the lowest clear bit is at index **1** $0b11\\underline{0}1$,\n> reset at index **0** $0b110\\underline{1}$ ->$12 (0b1100)$\n> $12 |_{or} 13 = 13$\n\n\u2714\uFE0F $11 (0b1011)$ \n> the lowest clear bit is at index **2** $0b1\\underline{0}11$\n> reset at index **1** $0b10\\underline{1}1$ -> $9(0b1001)$\n> $9 |_{or} 10 = 11$\n---\n# Algorithm\n\nTo extract the lowest clear bit the simplest way is to use the [asm instruction **blci**](https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set#TBM_(Trailing_Bit_Manipulation)) that can be written as ```x | ~(x+1)``` or ```x | -(x+2)```\ni.e.:\n> **bin**$(183) = 0b[0\\dots]10110111$\n> **blci**$(0b[0\\dots]10110111) = 0b[1\\dots]11110111$\n\nThe **blci** instruction will return a mask that has all bit set except the lowest 0.\n\nThen by shifting arithmetically right by 1 (**sar**) the mask will move with the clear bit set to the previous (the one we need to clear as previously stated).\n(N.B.we work with integer so the most significative bit is always 0 if positive, hence the logical shift is equivalent to the arithmetic in this case) \n> **sar**$(0b[1\\dots]11110111) = 0b[1\\dots]11111011 $\n\nThis will lead to the mask we need to apply to the original number to obtain the result\n> $0b[0\\dots]10110111$ **&** $0b[1\\dots]11111011 = 0b[0\\dots]10110011 $\n---\n# Code\n```cpp []\n// map(x:nums) -> get lowest clear bit from x, reset previous bit from x\n// if x>2 and trailing bit manipulation is supported,\n// the generated asm should look like:\n// blci eax, edi // r = x | ~(x+1)\n// sar eax // r >>= 1\n// and eax, edi // r &= x\n// ret\n// if not supported:\n// mov eax, -2 // r = -2\n// sub eax, edi // r -= x\n// or eax, edi // r |= x\n// sar eax // r >>= 1\n// and eax, edi // r &= x\n// ret\n\n#pragma GCC target("bmi,tbm")\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n vector<int> ret(nums.size());\n transform(nums.begin(), nums.end(), ret.begin(), [](int x){\n return x > 2 ? x & ((x | ~(x+1)) >> 1): -1;\n });\n return ret;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Concise code | Beats 100% | concise-code-beats-100-by-lokeshwar777-7liy | Code\npython3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n """\n a | a+1 = y = num\n y - a = (some p | lokeshwar777 | NORMAL | 2024-10-14T05:11:06.805868+00:00 | 2024-10-14T05:14:38.210840+00:00 | 35 | false | # Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n """\n a | a+1 = y = num\n y - a = (some power of 2) = (1 << i) i from 1 to 30\n a = y - (some power of 2)\n a | a+1 = num\n where a = num - (1<<i) i->1 to 30\n """\n\n def solve(num):\n if num == 2:\n return -1\n\n mini = num\n for i in range(31):\n a = num - (1 << i)\n if (a | (a + 1)) == num:\n mini = min(mini, a)\n return mini\n\n return [solve(num) for num in nums]\n\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | BEATS 100% | O(n) TIME COMPLEXITY | O(n) SPACE COMPLEXITY | PYTHON | BIT MANIPULATION | beats-100-on-time-complexity-on-space-co-orgu | Complexity\n- Time complexity:\nO(n) because we iterate through all numbers.\n\n- Space complexity:\nO(1)\n\n# Code\npython3 []\nclass Solution:\n def minBit | SergioBear | NORMAL | 2024-10-13T13:58:38.895234+00:00 | 2024-10-13T13:58:38.895269+00:00 | 38 | false | # Complexity\n- Time complexity:\n$$O(n)$$ because we iterate through all numbers.\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n\n for n in nums:\n if n == 2: # 10 (it\'s exactly this prime integer ending in 0)\n ans.append(-1)\n continue\n \n counter = 0 # maximum digit of a number that can be removed (to minimise each value ans[i])\n # 100011 -> 100001 OR (100001 + 1) \n # 100001\n # OR 100010 (next digit of a number)\n # -------\n # 100011\n # 1001 -> 1000 OR (1000 + 1)\n # 10111 -> 10011 OR (1011 + 1)\n \n num = n\n\n while n & 1 == 1:\n n >>= 1\n counter += 1\n\n ans.append(num - 2 ** (counter - 1))\n\n return ans\n``` | 2 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | cpp bitwise sol | cpp-bitwise-sol-by-madhavgarg2213-mnzc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach : if num =2 then push -1, otherwise check the last consecutive one from th | madhavgarg2213 | NORMAL | 2024-10-13T10:05:25.302834+00:00 | 2024-10-13T10:05:25.302873+00:00 | 22 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : if num =2 then push -1, otherwise check the last consecutive one from the right. now if u think ki we make that one 0 and then do OR of the new number with (new no +1) as it will have one on the removed pos for sure. now their both OR will return num \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> ans;\n\n for(int i : nums){\n if(i==2){\n ans.push_back(-1);\n continue;\n }\n int num = i;\n int c = 0;\n while(num & 1){\n c++;\n num /= 2;\n\n }\n ans.push_back(i - (pow(2,c-1)));\n }\n return ans;\n\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | C++ || Commented || | c-commented-by-khalidalam980-ka2x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | khalidalam980 | NORMAL | 2024-10-12T21:22:04.838546+00:00 | 2024-10-12T21:22:04.838576+00:00 | 48 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(32*n)$\n\n- Space complexity: $O(n)$ for storing result\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& nums) {\n int n = nums.size(); // Get the size of the input array\n vector<int> result; // Initialize a vector to store the results\n\n // Iterate over each number in the input array\n for(auto num : nums) {\n // If the number is 2, add -1 to the result vector\n if(num == 2) \n result.push_back(-1);\n else {\n // Try to find the first bit that is not set (0) in the number\n for(int i = 0; i <= 31; i++) {\n // Check if the bit at position i is 0\n if((num & (1 << i)) == 0) {\n // Flip the bit at position i-1\n num = num ^ (1 << (i-1));\n // Add the modified number to the result vector\n result.push_back(num);\n // Break the loop after modifying the number\n break;\n }\n }\n }\n }\n\n // Return the resulting vector\n return result;\n }\n};\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Bit Manipulation , not the best code. || PYTHON 3 || | easy-bit-manipulation-not-the-best-code-cke21 | Intuition\nI noticed a pattern. Basically, the only even prime number is 2, and it doesn\'t have a number x such that x | x+1 = 2. Now for all the other prime n | rahulSriram_25 | NORMAL | 2024-10-12T16:46:10.217542+00:00 | 2024-10-12T16:46:10.217573+00:00 | 16 | false | # Intuition\nI noticed a pattern. Basically, the only even prime number is 2, and it doesn\'t have a number `x` such that `x | x+1 = 2`. Now for all the other prime numbers, we need to understand the pattern in the bit representation.\n\nTake \n`3` => `11` and the answer was `1` => `1`\n`5` => `101` and the answer was `4` => `100`\n`11` => `1011` and the answer was `9` => `1001`\n`13` => `1101` and the answer was `12` => `1100`\n`31` => `11111` and the answer was `15` => `1111`\n\nIf you notice, in all the cases, the answer is just differing from the number by just **1 BIT**.\n\nAnd that bit, is the `(rightmost index of 0) + 1`.\nExample: 13 => `1101` the rightmost index is at index 2, and the bit at index 3 is flipped, to get the answer!\n\n\nAnd in cases like `31` where there is no `0`, then the first bit is the bit that is flipped! \n\n\n\n\n# Approach\nSo the problem boils down to finding the index of the `rightmost 0` and flipping the bit next to it.\n\n# Complexity\n- Time complexity:\nO(N) for traversing through the list of `nums`\nO(log10 K) for traversing through the bits of each number in binary representation, where K is the maximum number in `nums`\n\n```\nO( N log10 K )\n```\n\n\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n s = []\n\n for i in nums:\n if (i == 2): # because we know 2 doesn\'t have a solution\n s.append(-1)\n\n else:\n b = str(bin(i))[2:] # get the binary representation\n try:\n indx = b.rindex("0") + 1\n if (b[indx] == "0"):\n d = "1"\n else:\n d = "0"\n\n c = eval("0b" + b[:indx] + d + b[indx + 1 :]) # construct the new integer\n \n except ValueError: # incase 0 was not present in the binary representation\n c = eval("0b" + b[1:])\n \n s.append(eval(c))\n\n\n return s\n``` | 2 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | Java Clean Simple Solution | using BitManipulation | java-clean-simple-solution-using-bitmani-9a5x | Complexity\n- Time complexity:O(n*32)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# C | Shree_Govind_Jee | NORMAL | 2024-10-12T16:02:05.760198+00:00 | 2024-10-12T16:02:05.760233+00:00 | 194 | false | # Complexity\n- Time complexity:$$O(n*32)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int n = nums.size();\n \n int[] ans = new int[n];\n for (int i = 0; i < n; i++) {\n int num = nums.get(i);\n \n int minimalAns = Integer.MAX_VALUE;\n boolean flag = false;\n for (int bit = 0; bit < 31; bit++) {\n if (((num >> bit) & 1) == 1) {\n int bit_ = num & ~(1 << bit);\n if (bit_ < 0) {\n continue;\n }\n\n if ((bit_ | (bit_ + 1)) == num) {\n if (bit_ < minimalAns) {\n minimalAns = bit_;\n flag = true;\n }\n }\n }\n }\n\n if (flag) {\n ans[i] = minimalAns;\n } else {\n ans[i] = -1;\n }\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'Bitmask', 'Java'] | 1 |
construct-the-minimum-bitwise-array-ii | Bit manipulation || beats 100% || very easy, simple analysis || c++ | bit-manipulation-beats-100-very-easy-sim-anmp | IntuitionOur intution is based on observing a pattern.
If the number is even then no solution is possible. We can prove this by contradiction, suppose we get a | sanmaika | NORMAL | 2025-03-15T19:31:59.646857+00:00 | 2025-03-15T19:31:59.646857+00:00 | 13 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Our intution is based on observing a pattern.
If the number is even then no solution is possible. We can prove this by contradiction, suppose we get a no (say k) such that k | k+1 = v, where v belongs to nums and is even. Two cases are possible:
1. If the lsb of k is 0 then lsb of k+1 should be 1 (which means if k is even then K=1 has to be odd)
OR
2. If k is odd then k+1 should be even.
So if we or the least significant bits of any no. (here k) with its next higher integer then the lsb will always be 1 (0 | 1 : in first case, 1 | 0 in the second case). Any even no will never have it's lsb==1. So for even v no such k exists.
If the no. is odd then one soltuion always exists that is equal to no. - 1 as if we substract 1 from an odd no. then we get the lsb toggled while keeping the rest of the bits same. But there can be one more solution. For eg. take 11, 10 | 11 will give u 11 but so will 9 | 10. If we expand 11 in binary we get 1011. 9 in binary is 1001 which is formed by unsetting the rightmost bit after first unset bit.
Similarly for 101**01**11 the answer would be 101**00**11. This is because 111 of 1010**111** can be written as => **011 + 1**. 011 belongs to 1010**011** and adding a 1 to this no would give us 1010100 and or of these two nos will give the result 1010111.
# Approach
<!-- Describe your approach to solving the problem. -->
We will traverse in the array nums and first check the parity of the number. If the number is even then push back in the answer array -1. if the no is odd then we need to find the ith bit at which the we get the first 0. It means that from the i-1 th bit to the lsb we have all ones in the binary representation of the number. To toggle the i-1 th bit we can xor the original number with a number that has only the i -1 th bit set.
**1010111 ^ 0000100 = 1010011**
0000100 is number that is power of two. Any number which has one bit set is a power of two. So we can right shift 1 by i-1 no. of places to get this number and xor it with the original integer.
# Complexity
- Time complexity: O(n*log(k)) where k = no of bits in every integer
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector<int> ans;
for(int num: nums){
// if even no such no. exists, so -1
if(! (num & 1) ) ans.push_back(-1);
// if no. is odd
else{
int i=0; // i carries the bit index. Initially 0.
int n = num; // n is a copy if num.
while(n){
// while u are getting a 1 at lsb, keep looping
if(n & 1) {
i++; // increment i
n = n>>1; // left shift to get the next bit as lsb
}
else{
// i bits were one, so we need to toggle the i th bit for which we need 1 only at the i th bit, this can be done by right sift operator
int p= 1<< (i-1); // cout<<p<<" "<<i<<" "<< n<<endl;
// xor the value to get the no.
n = num^p;
// we have found the result so break. n contains the result
break;
}
}
if(n!=0) ans.push_back(n);
// if n==0 => n is 2^k -1 type of a no. If the loop broke because n==0 then else part in the
// while loop would not have been calculated. A no. for which all the bits are ones (2^k -1)
// the optimal soln is the number formed by taking all the bits except msb that can be done by
// dividing the original no. by 2 (it's equivalent is left shift the no. by 1)
else ans.push_back(num>>1);
}
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | BEATS 100% || O(N) EASY SOLUTION :- | beats-100-on-easy-solution-by-rxhabh-6zoz | IntuitionApproachCheck for even numbers:The condition ans[i] OR (ans[i] + 1) = nums[i] is impossible to satisfy for even numbers because the result of ans[i] OR | Rxhabh_ | NORMAL | 2024-12-24T02:54:21.640731+00:00 | 2024-12-24T02:54:21.640731+00:00 | 27 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
Check for even numbers:
The condition ans[i] OR (ans[i] + 1) = nums[i] is impossible to satisfy for even numbers because the result of ans[i] OR (ans[i] + 1) is always an odd number, while nums[i] is even.
Therefore, for any even nums[i], you directly set nums[i] = -1 and move to the next element.
For odd numbers:
Convert each nums[i] to a bitset<30>. This allows you to work with the binary representation of nums[i] easily, as each bitset will represent a 30-bit binary number (enough to handle prime numbers up to 10^9).
Find the smallest ans[i]:
Bit Manipulation:
Iterate through the bits of nums[i] (from the least significant bit to the most significant bit).
If a bit is 0, toggle it to 0 (this is done in the inner loop).
Then, compute the corresponding value x from the modified bitset.
Check the condition:
Once the modified x is computed, check if x | (x + 1) == nums[i]. If this condition is satisfied, then x is the answer.
If the condition is not met, increment x and check again until you find a valid x.
# Complexity
- Time complexity:
- O(N)
- Space complexity:
- O(1)
# Code
```cpp []
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++) {
// Step 1: Check if the number is even
if(nums[i] % 2 == 0) {
nums[i] = -1; // For even numbers, it's not possible
continue;
}
// Step 2: Convert the number to a bitset to work with its binary representation
bitset<30> b(nums[i]);
// Step 3: Modify the bitset to find the smallest valid number
for(int j = 0; j < 30; j++) {
if(b[j] == 0) {
j--; // Rewind to the previous bit
b[j] = 0; // Reset the bit to 0
break;
}
}
// Step 4: Compute the modified number from the bitset
int x = 0, a = 1;
for(int j = 0; j < 30; j++) {
x += (a * b[j]);
a *= 2;
}
// Step 5: Check if this x satisfies the condition or increment until it does
while(x <= nums[i] - 1) {
if((x | (x + 1)) == nums[i]) {
nums[i] = x;
break;
}
x++; // Increment x until we find a valid answer
}
}
// Return the modified array
return nums;
}
};
``` | 1 | 0 | ['C++'] | 0 |
construct-the-minimum-bitwise-array-ii | Rust bitwise | rust-bitwise-by-maxime002-v4qd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Maxime002 | NORMAL | 2024-10-13T00:38:35.212484+00:00 | 2024-10-13T00:38:35.212517+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```rust []\nimpl Solution {\n pub fn min_bitwise_array(nums: Vec<i32>) -> Vec<i32> {\n nums.into_iter().map(|n| \n if n % 2 == 0 {\n -1 \n } else {\n n & !(1 << (n.trailing_ones() - 1))\n }\n ).collect()\n }\n}\n``` | 1 | 0 | ['Rust'] | 0 |
construct-the-minimum-bitwise-array-ii | Very Easy beats 100% | very-easy-beats-100-by-shiv19_03-ntyp | Intuition\nYou need to turn off the rightmost bit from the left side consecutive ones.\n\n# Approach\nFor a number 111000011111 the solution is always1110000011 | Shiv19_03 | NORMAL | 2024-10-12T18:03:04.611487+00:00 | 2024-10-12T23:57:19.416503+00:00 | 16 | false | # Intuition\nYou need to turn off the rightmost bit from the left side consecutive ones.\n\n# Approach\nFor a number `111000011111` the solution is always`111000001111`.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ --> size of array || Don\'t worry about the solve function the bit length is at max 32.\n\n- Space complexity:\n$$O(n)$$ --> The solution array.\n\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n ans = []\n\n def solve(num):\n bits = bin(num)[2:]\n x = 0\n for i in range(len(bits)-1,-1,-1):\n if bits[i] == \'1\':\n x = i\n continue\n else:\n break\n val = bits[:x]+\'0\'+bits[x+1:]\n return int(val,2)\n \n for num in nums:\n if num == 2:\n ans.append(-1)\n else:\n ans.append(solve(num))\n return ans \n``` | 1 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | One Liner Python3. | one-liner-python3-by-sandeep_p-poad | Approach\nfind leftmost 1 in rightmost sequence of 1s and flip it.\ny=x^(x+1) gives mask including rightmost 0.\nflip second most significant bit of y in x.\n# | sandeep_p | NORMAL | 2024-10-12T16:50:20.151419+00:00 | 2024-10-12T17:09:27.281205+00:00 | 14 | false | # Approach\nfind leftmost 1 in rightmost sequence of 1s and flip it.\n`y=x^(x+1)` gives mask including rightmost 0.\nflip second most significant bit of y in x.\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\n```python3 []\nclass Solution:\n def minBitwiseArray(self, nums: List[int]) -> List[int]:\n return [-1 if x==2 else x^ ( (x^(x+1)) >>1 ) ^ ( (x^(x+1)) >>2 ) for x in nums]\n``` | 1 | 0 | ['Python3'] | 0 |
construct-the-minimum-bitwise-array-ii | Easy Solution | Whithout shift operator | Simple logic | easy-solution-whithout-shift-operator-si-lm03 | Approach\nLoop through the input list of numbers:\nFor each number in the list nums, we find the smallest possible i for that number.\n\nWe iterate through each | kbhanu5125 | NORMAL | 2024-10-12T16:49:46.017886+00:00 | 2024-10-12T16:49:46.017911+00:00 | 87 | false | # Approach\nLoop through the input list of numbers:\nFor each number in the list nums, we find the smallest possible i for that number.\n\nWe iterate through each bit of num from the most significant bit (MSB) to the least significant bit (LSB).\nFor each bit, we flip that bit (change 1 to 0 or 0 to 1) and check if the modified number satisfies the condition ```i \u2223 (i+1) == num.```\nIf we find such a number i, we return it.\nIf no such number is found after trying all bits, return -1.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```java []\nclass Solution {\n public int[] minBitwiseArray(List<Integer> nums) {\n int ans[] = new int[nums.size()];\n for(int i = 0; i < nums.size(); i++)\n {\n int flag = 0;\n int v = nums.get(i);\n String b = Integer.toBinaryString(v);\n \n for(int j = 0; j < b.length(); j++)\n {\n if(b.charAt(j) == \'1\')\n {\n String b1 = b.substring(0,j) + \'0\' + b.substring(j+1);\n int v1 = Integer.parseInt(b1, 2);\n if((v1 | (v1 + 1)) == v)\n {\n ans[i] = v1;\n flag = 1;\n break;\n }\n }\n }\n if(flag == 0)\n ans[i] = -1;\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Array', 'String', 'Bit Manipulation', 'Bitmask', 'Java'] | 1 |
construct-the-minimum-bitwise-array-ii | C++, bit mask, and I tried to explain | c-bit-mask-and-i-tried-to-explain-by-jai-dxbu | Basics -\n1. All prime numbers are odd except 2.\n2. 2 does not have any solution. Push back -1 for 2.\n3. All odd numbers will always have atleast one solution | jain-priyanshu | NORMAL | 2024-10-12T16:33:50.395711+00:00 | 2024-10-12T16:33:50.395732+00:00 | 227 | false | # Basics -\n1. All prime numbers are odd except 2.\n2. 2 does not have any solution. Push back -1 for 2.\n3. All odd numbers will always have atleast one solution: (x BITWISEOR (x-1)) = x. This works because all odd numbers have lowest bit 1 and the number just before that will be the same number but wit lowest bit as 0. Example 7 -> 111, 7-1=6 -> 110\n\n# Intuition\nI was able to get the idea after my intial solution failed for test case [47] (answer is 39)\n\n47 -> 10`1`111\n\n39 -> 100111\n40 -> 101000\n\nHere we unset the highest set bit next to first unset bit (from right). In this case first unset bit is the 4th idx from right. So 3rd index (set bit) needs to be unset.\n\nWhy does this work?\n\nFirst we lose 1 bit from our original number 47.\n\nThen we get the same bit back when we do a +1 to 39.\n\n40 has all the same bits as 47 except the lower bits which are preserverd in 37.\n\nWe are esentially dividing the whole binary string in 2 parts - left and right of 1st zero (first 0 from right). \n\nThe lower bits are stored in the smaller number and when we add +1 to a number in binary, all lower set bits become unset and first unset bit from right becomes set, so the bigger number has all higher bits (including the one we unset).\n\nEx: 7 + 1 = 8\n7 ->0111\n1 -> 0001\n8 -> 1000\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> minBitwiseArray(vector<int>& arr) {\n int n = arr.size();\n\n vector<int> res;\n\n for(int curr : arr){\n if(curr == 2){\n res.push_back(-1);\n continue;\n }\n\n int mask = 1;\n\n for(int i = 0; i < 31; i++){\n if((curr & (1 << i)) == 0){\n // found first 0, use mask from last set bit\n // assume mask = 00100\n // then ~mask becomes 11011\n // this way we unset only one bit in curr\n int ans = (curr & (~mask));\n res.push_back(ans);\n break;\n }\n\n // keep creating the mask until we find first 0\n mask = (1 << i);\n }\n\n }\n\n return res;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'Bitmask', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.