id
int64
1
3.63k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
98
Validate Binary Search Tree
Medium
<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p> <p>A <strong>valid BST</strong> is defined as follows:</p> <ul> <li>The left <span data-keyword="subtree">subtree</span> of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li> <li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li> <li>Both the left and right subtrees must also be binary search trees.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree1.jpg" style="width: 302px; height: 182px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0098.Validate%20Binary%20Search%20Tree/images/tree2.jpg" style="width: 422px; height: 292px;" /> <pre> <strong>Input:</strong> root = [5,1,4,null,null,3,6] <strong>Output:</strong> false <strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function isValidBST(root: TreeNode | null): boolean { let prev: TreeNode | null = null; const dfs = (root: TreeNode | null): boolean => { if (!root) { return true; } if (!dfs(root.left)) { return false; } if (prev && prev.val >= root.val) { return false; } prev = root; return dfs(root.right); }; return dfs(root); }
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * 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: void recoverTree(TreeNode* root) { TreeNode* prev = nullptr; TreeNode* first = nullptr; TreeNode* second = nullptr; function<void(TreeNode * root)> dfs = [&](TreeNode* root) { if (!root) return; dfs(root->left); if (prev && prev->val > root->val) { if (!first) first = prev; second = root; } prev = root; dfs(root->right); }; dfs(root); swap(first->val, second->val); } };
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private TreeNode prev, first, second; public void RecoverTree(TreeNode root) { dfs(root); int t = first.val; first.val = second.val; second.val = t; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); if (prev != null && prev.val > root.val) { if (first == null) { first = prev; } second = root; } prev = root; dfs(root.right); } }
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func recoverTree(root *TreeNode) { var prev, first, second *TreeNode var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) if prev != nil && prev.Val > root.Val { if first == nil { first = prev } second = root } prev = root dfs(root.Right) } dfs(root) first.Val, second.Val = second.Val, first.Val }
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private TreeNode prev; private TreeNode first; private TreeNode second; public void recoverTree(TreeNode root) { dfs(root); int t = first.val; first.val = second.val; second.val = t; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); if (prev != null && prev.val > root.val) { if (first == null) { first = prev; } second = root; } prev = root; dfs(root.right); } }
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var recoverTree = function (root) { let prev = null; let first = null; let second = null; function dfs(root) { if (!root) { return; } dfs(root.left); if (prev && prev.val > root.val) { if (!first) { first = prev; } second = root; } prev = root; dfs(root.right); } dfs(root); const t = first.val; first.val = second.val; second.val = t; };
99
Recover Binary Search Tree
Medium
<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg" style="width: 422px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,3,null,null,2] <strong>Output:</strong> [3,1,null,null,2] <strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg" style="width: 581px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,null,2] <strong>Output:</strong> [2,1,4,null,null,3] <strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li> <li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recoverTree(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. """ def dfs(root): if root is None: return nonlocal prev, first, second dfs(root.left) if prev and prev.val > root.val: if first is None: first = prev second = root prev = root dfs(root.right) prev = first = second = None dfs(root) first.val, second.val = second.val, first.val
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * 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: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == q) return true; if (!p || !q || p->val != q->val) return false; return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } };
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isSameTree(p *TreeNode, q *TreeNode) bool { if p == q { return true } if p == nil || q == nil || p.Val != q.Val { return false } return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) }
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == q) return true; if (p == null || q == null || p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} p * @param {TreeNode} q * @return {boolean} */ var isSameTree = function (p, q) { if (!p && !q) return true; if (p && q) { return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } return false; };
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
PHP
/** * Definition for a binary tree node. * class TreeNode { * public $val = null; * public $left = null; * public $right = null; * function __construct($val = 0, $left = null, $right = null) { * $this->val = $val; * $this->left = $left; * $this->right = $right; * } * } */ class Solution { /** * @param TreeNode $p * @param TreeNode $q * @return Boolean */ function isSameTree($p, $q) { if ($p == null && $q == null) { return true; } if ($p == null || $q == null) { return false; } if ($p->val != $q->val) { return false; } return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); } }
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: if p == q: return True if p is None or q is None or p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(p: &Option<Rc<RefCell<TreeNode>>>, q: &Option<Rc<RefCell<TreeNode>>>) -> bool { if p.is_none() && q.is_none() { return true; } if p.is_none() || q.is_none() { return false; } let r1 = p.as_ref().unwrap().borrow(); let r2 = q.as_ref().unwrap().borrow(); r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right) } pub fn is_same_tree( p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>, ) -> bool { Self::dfs(&p, &q) } }
100
Same Tree
Easy
<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p> <p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex1.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,3], q = [1,2,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex2.jpg" style="width: 382px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2], q = [1,null,2] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0100.Same%20Tree/images/ex3.jpg" style="width: 622px; height: 182px;" /> <pre> <strong>Input:</strong> p = [1,2,1], q = [1,1,2] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { if (p == null && q == null) { return true; } if (p == null || q == null || p.val !== q.val) { return false; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * 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: bool isSymmetric(TreeNode* root) { auto dfs = [&](this auto&& dfs, TreeNode* root1, TreeNode* root2) -> bool { if (root1 == root2) { return true; } if (!root1 || !root2 || root1->val != root2->val) { return false; } return dfs(root1->left, root2->right) && dfs(root1->right, root2->left); }; return dfs(root->left, root->right); } };
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isSymmetric(root *TreeNode) bool { var dfs func(root1, root2 *TreeNode) bool dfs = func(root1, root2 *TreeNode) bool { if root1 == root2 { return true } if root1 == nil || root2 == nil || root1.Val != root2.Val { return false } return dfs(root1.Left, root2.Right) && dfs(root1.Right, root2.Left) } return dfs(root.Left, root.Right) }
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isSymmetric(TreeNode root) { return dfs(root.left, root.right); } private boolean dfs(TreeNode root1, TreeNode root2) { if (root1 == root2) { return true; } if (root1 == null || root2 == null || root1.val != root2.val) { return false; } return dfs(root1.left, root2.right) && dfs(root1.right, root2.left); } }
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isSymmetric = function (root) { const dfs = (root1, root2) => { if (root1 === root2) { return true; } if (!root1 || !root2 || root1.val !== root2.val) { return false; } return dfs(root1.left, root2.right) && dfs(root1.right, root2.left); }; return dfs(root.left, root.right); };
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: def dfs(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: if root1 == root2: return True if root1 is None or root2 is None or root1.val != root2.val: return False return dfs(root1.left, root2.right) and dfs(root1.right, root2.left) return dfs(root.left, root.right)
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool { fn dfs(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>) -> bool { match (root1, root2) { (Some(node1), Some(node2)) => { let node1 = node1.borrow(); let node2 = node2.borrow(); node1.val == node2.val && dfs(node1.left.clone(), node2.right.clone()) && dfs(node1.right.clone(), node2.left.clone()) } (None, None) => true, _ => false, } } match root { Some(root) => dfs(root.borrow().left.clone(), root.borrow().right.clone()), None => true, } } }
101
Symmetric Tree
Easy
<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree1.jpg" style="width: 354px; height: 291px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,4,4,3] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0101.Symmetric%20Tree/images/symtree2.jpg" style="width: 308px; height: 258px;" /> <pre> <strong>Input:</strong> root = [1,2,2,null,3,null,3] <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it both recursively and iteratively?
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function isSymmetric(root: TreeNode | null): boolean { const dfs = (root1: TreeNode | null, root2: TreeNode | null): boolean => { if (root1 === root2) { return true; } if (!root1 || !root2 || root1.val !== root2.val) { return false; } return dfs(root1.left, root2.right) && dfs(root1.right, root2.left); }; return dfs(root.left, root.right); }
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
C++
/** * 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<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; if (!root) return ans; queue<TreeNode*> q{{root}}; while (!q.empty()) { vector<int> t; for (int n = q.size(); n; --n) { auto node = q.front(); q.pop(); t.push_back(node->val); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } ans.push_back(t); } return ans; } };
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func levelOrder(root *TreeNode) (ans [][]int) { if root == nil { return } q := []*TreeNode{root} for len(q) > 0 { t := []int{} for n := len(q); n > 0; n-- { node := q[0] q = q[1:] t = append(t, node.Val) if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } ans = append(ans, t) } return }
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { List<Integer> t = new ArrayList<>(); for (int n = q.size(); n > 0; --n) { TreeNode node = q.poll(); t.add(node.val); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } ans.add(t); } return ans; } }
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[][]} */ var levelOrder = function (root) { const ans = []; if (!root) { return ans; } const q = [root]; while (q.length) { const t = []; const qq = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(t); q.splice(0, q.length, ...qq); } return ans; };
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) while q: t = [] for _ in range(len(q)): node = q.popleft() t.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(t) return ans
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { let mut ans = Vec::new(); if let Some(root_node) = root { let mut q = VecDeque::new(); q.push_back(root_node); while !q.is_empty() { let mut t = Vec::new(); for _ in 0..q.len() { if let Some(node) = q.pop_front() { let node_ref = node.borrow(); t.push(node_ref.val); if let Some(ref left) = node_ref.left { q.push_back(Rc::clone(left)); } if let Some(ref right) = node_ref.right { q.push_back(Rc::clone(right)); } } } ans.push(t); } } ans } }
102
Binary Tree Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[9,20],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function levelOrder(root: TreeNode | null): number[][] { const ans: number[][] = []; if (!root) { return ans; } const q: TreeNode[] = [root]; while (q.length) { const t: number[] = []; const qq: TreeNode[] = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(t); q.splice(0, q.length, ...qq); } return ans; }
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
C++
/** * 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<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> ans; if (!root) { return ans; } queue<TreeNode*> q{{root}}; int left = 1; while (!q.empty()) { vector<int> t; for (int n = q.size(); n; --n) { auto node = q.front(); q.pop(); t.emplace_back(node->val); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } if (!left) { reverse(t.begin(), t.end()); } ans.emplace_back(t); left ^= 1; } return ans; } };
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func zigzagLevelOrder(root *TreeNode) (ans [][]int) { if root == nil { return } q := []*TreeNode{root} left := true for len(q) > 0 { t := []int{} for n := len(q); n > 0; n-- { node := q[0] q = q[1:] t = append(t, node.Val) if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } if !left { for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 { t[i], t[j] = t[j], t[i] } } ans = append(ans, t) left = !left } return }
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) { return ans; } Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); boolean left = true; while (!q.isEmpty()) { List<Integer> t = new ArrayList<>(); for (int n = q.size(); n > 0; --n) { TreeNode node = q.poll(); t.add(node.val); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } if (!left) { Collections.reverse(t); } ans.add(t); left = !left; } return ans; } }
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[][]} */ var zigzagLevelOrder = function (root) { const ans = []; if (!root) { return ans; } const q = [root]; let left = 1; while (q.length) { const t = []; const qq = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(left ? t : t.reverse()); q.splice(0, q.length, ...qq); left ^= 1; } return ans; };
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) ans = [] left = 1 while q: t = [] for _ in range(len(q)): node = q.popleft() t.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(t if left else t[::-1]) left ^= 1 return ans
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn zigzag_level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { let mut ans = Vec::new(); let mut left = true; if let Some(root_node) = root { let mut q = VecDeque::new(); q.push_back(root_node); while !q.is_empty() { let mut t = Vec::new(); for _ in 0..q.len() { if let Some(node) = q.pop_front() { let node_ref = node.borrow(); t.push(node_ref.val); if let Some(ref left) = node_ref.left { q.push_back(Rc::clone(left)); } if let Some(ref right) = node_ref.right { q.push_back(Rc::clone(right)); } } } if !left { t.reverse(); } ans.push(t); left = !left; } } ans } }
103
Binary Tree Zigzag Level Order Traversal
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[3],[20,9],[15,7]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function zigzagLevelOrder(root: TreeNode | null): number[][] { const ans: number[][] = []; if (!root) { return ans; } const q: TreeNode[] = [root]; let left: number = 1; while (q.length) { const t: number[] = []; const qq: TreeNode[] = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(left ? t : t.reverse()); q.splice(0, q.length, ...qq); left ^= 1; } return ans; }
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #define max(a, b) (((a) > (b)) ? (a) : (b)) int maxDepth(struct TreeNode* root) { if (!root) { return 0; } int left = maxDepth(root->left); int right = maxDepth(root->right); return 1 + max(left, right); }
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * 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: int maxDepth(TreeNode* root) { if (!root) return 0; int l = maxDepth(root->left), r = maxDepth(root->right); return 1 + max(l, r); } };
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func maxDepth(root *TreeNode) int { if root == nil { return 0 } l, r := maxDepth(root.Left), maxDepth(root.Right) return 1 + max(l, r) }
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int l = maxDepth(root.left); int r = maxDepth(root.right); return 1 + Math.max(l, r); } }
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var maxDepth = function (root) { if (!root) return 0; const l = maxDepth(root.left); const r = maxDepth(root.right); return 1 + Math.max(l, r); };
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 l, r = self.maxDepth(root.left), self.maxDepth(root.right) return 1 + max(l, r)
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 { if root.is_none() { return 0; } let node = root.as_ref().unwrap().borrow(); 1 + Self::dfs(&node.left).max(Self::dfs(&node.right)) } pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { Self::dfs(&root) } }
104
Maximum Depth of Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p> <p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/images/tmp-tree.jpg" style="width: 400px; height: 277px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1,null,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function maxDepth(root: TreeNode | null): number { if (root === null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
C++
/** * 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: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int n = preorder.size(); unordered_map<int, int> d; for (int i = 0; i < n; ++i) { d[inorder[i]] = i; } function<TreeNode*(int, int, int)> dfs = [&](int i, int j, int n) -> TreeNode* { if (n <= 0) { return nullptr; } int v = preorder[i]; int k = d[v]; TreeNode* l = dfs(i + 1, j, k - j); TreeNode* r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); return new TreeNode(v, l, r); }; return dfs(0, 0, n); } };
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func buildTree(preorder []int, inorder []int) *TreeNode { d := map[int]int{} for i, x := range inorder { d[x] = i } var dfs func(i, j, n int) *TreeNode dfs = func(i, j, n int) *TreeNode { if n <= 0 { return nil } v := preorder[i] k := d[v] l := dfs(i+1, j, k-j) r := dfs(i+1+k-j, k+1, n-1-(k-j)) return &TreeNode{v, l, r} } return dfs(0, 0, len(preorder)) }
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int[] preorder; private Map<Integer, Integer> d = new HashMap<>(); public TreeNode buildTree(int[] preorder, int[] inorder) { int n = preorder.length; this.preorder = preorder; for (int i = 0; i < n; ++i) { d.put(inorder[i], i); } return dfs(0, 0, n); } private TreeNode dfs(int i, int j, int n) { if (n <= 0) { return null; } int v = preorder[i]; int k = d.get(v); TreeNode l = dfs(i + 1, j, k - j); TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); return new TreeNode(v, l, r); } }
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[]} preorder * @param {number[]} inorder * @return {TreeNode} */ var buildTree = function (preorder, inorder) { const d = new Map(); const n = inorder.length; for (let i = 0; i < n; ++i) { d.set(inorder[i], i); } const dfs = (i, j, n) => { if (n <= 0) { return null; } const v = preorder[i]; const k = d.get(v); const l = dfs(i + 1, j, k - j); const r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); return new TreeNode(v, l, r); }; return dfs(0, 0, n); };
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: def dfs(i: int, j: int, n: int) -> Optional[TreeNode]: if n <= 0: return None v = preorder[i] k = d[v] l = dfs(i + 1, j, k - j) r = dfs(i + 1 + k - j, k + 1, n - k + j - 1) return TreeNode(v, l, r) d = {v: i for i, v in enumerate(inorder)} return dfs(0, 0, len(preorder))
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; impl Solution { pub fn build_tree(preorder: Vec<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { let mut d = HashMap::new(); for (i, &x) in inorder.iter().enumerate() { d.insert(x, i); } Self::dfs(&preorder, &d, 0, 0, preorder.len()) } pub fn dfs( preorder: &Vec<i32>, d: &HashMap<i32, usize>, i: usize, j: usize, n: usize, ) -> Option<Rc<RefCell<TreeNode>>> { if n <= 0 { return None; } let v = preorder[i]; let k = d[&v]; let mut root = TreeNode::new(v); root.left = Self::dfs(preorder, d, i + 1, j, k - j); root.right = Self::dfs(preorder, d, i + k - j + 1, k + 1, n - k + j - 1); Some(Rc::new(RefCell::new(root))) } }
105
Construct Binary Tree from Preorder and Inorder Traversal
Medium
<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> preorder = [-1], inorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= preorder.length &lt;= 3000</code></li> <li><code>inorder.length == preorder.length</code></li> <li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li> <li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li> <li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function buildTree(preorder: number[], inorder: number[]): TreeNode | null { const d: Map<number, number> = new Map(); const n = inorder.length; for (let i = 0; i < n; ++i) { d.set(inorder[i], i); } const dfs = (i: number, j: number, n: number): TreeNode | null => { if (n <= 0) { return null; } const v = preorder[i]; const k = d.get(v)!; const l = dfs(i + 1, j, k - j); const r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); return new TreeNode(v, l, r); }; return dfs(0, 0, n); }
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
C++
/** * 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: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { unordered_map<int, int> d; int n = inorder.size(); for (int i = 0; i < n; ++i) { d[inorder[i]] = i; } function<TreeNode*(int, int, int)> dfs = [&](int i, int j, int n) -> TreeNode* { if (n <= 0) { return nullptr; } int v = postorder[j + n - 1]; int k = d[v]; auto l = dfs(i, j, k - i); auto r = dfs(k + 1, j + k - i, n - k + i - 1); return new TreeNode(v, l, r); }; return dfs(0, 0, n); } };
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func buildTree(inorder []int, postorder []int) *TreeNode { d := map[int]int{} for i, v := range inorder { d[v] = i } var dfs func(i, j, n int) *TreeNode dfs = func(i, j, n int) *TreeNode { if n <= 0 { return nil } v := postorder[j+n-1] k := d[v] l := dfs(i, j, k-i) r := dfs(k+1, j+k-i, n-k+i-1) return &TreeNode{v, l, r} } return dfs(0, 0, len(inorder)) }
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private Map<Integer, Integer> d = new HashMap<>(); private int[] postorder; public TreeNode buildTree(int[] inorder, int[] postorder) { this.postorder = postorder; int n = inorder.length; for (int i = 0; i < n; ++i) { d.put(inorder[i], i); } return dfs(0, 0, n); } private TreeNode dfs(int i, int j, int n) { if (n <= 0) { return null; } int v = postorder[j + n - 1]; int k = d.get(v); TreeNode l = dfs(i, j, k - i); TreeNode r = dfs(k + 1, j + k - i, n - k + i - 1); return new TreeNode(v, l, r); } }
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def dfs(i: int, j: int, n: int) -> Optional[TreeNode]: if n <= 0: return None v = postorder[j + n - 1] k = d[v] l = dfs(i, j, k - i) r = dfs(k + 1, j + k - i, n - k + i - 1) return TreeNode(v, l, r) d = {v: i for i, v in enumerate(inorder)} return dfs(0, 0, len(inorder))
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; impl Solution { pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { let n = inorder.len(); let mut d: HashMap<i32, usize> = HashMap::new(); for i in 0..n { d.insert(inorder[i], i); } fn dfs( postorder: &[i32], d: &HashMap<i32, usize>, i: usize, j: usize, n: usize, ) -> Option<Rc<RefCell<TreeNode>>> { if n <= 0 { return None; } let val = postorder[j + n - 1]; let k = *d.get(&val).unwrap(); let left = dfs(postorder, d, i, j, k - i); let right = dfs(postorder, d, k + 1, j + k - i, n - 1 - (k - i)); Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) } dfs(&postorder, &d, 0, 0, n) } }
106
Construct Binary Tree from Inorder and Postorder Traversal
Medium
<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/images/tree.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] <strong>Output:</strong> [3,9,20,null,null,15,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> inorder = [-1], postorder = [-1] <strong>Output:</strong> [-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= inorder.length &lt;= 3000</code></li> <li><code>postorder.length == inorder.length</code></li> <li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li> <li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li> <li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li> <li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li> <li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li> </ul>
Tree; Array; Hash Table; Divide and Conquer; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function buildTree(inorder: number[], postorder: number[]): TreeNode | null { const n = inorder.length; const d: Record<number, number> = {}; for (let i = 0; i < n; i++) { d[inorder[i]] = i; } const dfs = (i: number, j: number, n: number): TreeNode | null => { if (n <= 0) { return null; } const v = postorder[j + n - 1]; const k = d[v]; const l = dfs(i, j, k - i); const r = dfs(k + 1, j + k - i, n - 1 - (k - i)); return new TreeNode(v, l, r); }; return dfs(0, 0, n); }
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
C++
/** * 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<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> ans; if (!root) { return ans; } queue<TreeNode*> q{{root}}; while (!q.empty()) { vector<int> t; for (int n = q.size(); n; --n) { auto node = q.front(); q.pop(); t.push_back(node->val); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } ans.push_back(t); } reverse(ans.begin(), ans.end()); return ans; } };
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func levelOrderBottom(root *TreeNode) (ans [][]int) { if root == nil { return } q := []*TreeNode{root} for len(q) > 0 { t := []int{} for n := len(q); n > 0; n-- { node := q[0] q = q[1:] t = append(t, node.Val) if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } ans = append(ans, t) } for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { ans[i], ans[j] = ans[j], ans[i] } return }
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { LinkedList<List<Integer>> ans = new LinkedList<>(); if (root == null) { return ans; } Deque<TreeNode> q = new LinkedList<>(); q.offerLast(root); while (!q.isEmpty()) { List<Integer> t = new ArrayList<>(); for (int i = q.size(); i > 0; --i) { TreeNode node = q.pollFirst(); t.add(node.val); if (node.left != null) { q.offerLast(node.left); } if (node.right != null) { q.offerLast(node.right); } } ans.addFirst(t); } return ans; } }
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[][]} */ var levelOrderBottom = function (root) { const ans = []; if (!root) { return ans; } const q = [root]; while (q.length) { const t = []; const qq = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(t); q.splice(0, q.length, ...qq); } return ans.reverse(); };
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: ans = [] if root is None: return ans q = deque([root]) while q: t = [] for _ in range(len(q)): node = q.popleft() t.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) ans.append(t) return ans[::-1]
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::{cell::RefCell, collections::VecDeque, rc::Rc}; impl Solution { pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { let mut ans = Vec::new(); if let Some(root_node) = root { let mut q = VecDeque::new(); q.push_back(root_node); while !q.is_empty() { let mut t = Vec::new(); for _ in 0..q.len() { if let Some(node) = q.pop_front() { let node_ref = node.borrow(); t.push(node_ref.val); if let Some(ref left) = node_ref.left { q.push_back(Rc::clone(left)); } if let Some(ref right) = node_ref.right { q.push_back(Rc::clone(right)); } } } ans.push(t); } } ans.reverse(); ans } }
107
Binary Tree Level Order Traversal II
Medium
<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/images/tree1.jpg" style="width: 277px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> [[15,7],[9,20],[3]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> [[1]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function levelOrderBottom(root: TreeNode | null): number[][] { const ans: number[][] = []; if (!root) { return ans; } const q: TreeNode[] = [root]; while (q.length) { const t: number[] = []; const qq: TreeNode[] = []; for (const { val, left, right } of q) { t.push(val); left && qq.push(left); right && qq.push(right); } ans.push(t); q.splice(0, q.length, ...qq); } return ans.reverse(); }
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
C++
/** * 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: TreeNode* sortedArrayToBST(vector<int>& nums) { auto dfs = [&](this auto&& dfs, int l, int r) -> TreeNode* { if (l > r) { return nullptr; } int mid = (l + r) >> 1; return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); }; return dfs(0, nums.size() - 1); } };
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { private int[] nums; public TreeNode SortedArrayToBST(int[] nums) { this.nums = nums; return dfs(0, nums.Length - 1); } private TreeNode dfs(int l, int r) { if (l > r) { return null; } int mid = (l + r) >> 1; return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); } }
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sortedArrayToBST(nums []int) *TreeNode { var dfs func(int, int) *TreeNode dfs = func(l, r int) *TreeNode { if l > r { return nil } mid := (l + r) >> 1 return &TreeNode{nums[mid], dfs(l, mid-1), dfs(mid+1, r)} } return dfs(0, len(nums)-1) }
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int[] nums; public TreeNode sortedArrayToBST(int[] nums) { this.nums = nums; return dfs(0, nums.length - 1); } private TreeNode dfs(int l, int r) { if (l > r) { return null; } int mid = (l + r) >> 1; return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); } }
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[]} nums * @return {TreeNode} */ var sortedArrayToBST = function (nums) { const dfs = (l, r) => { if (l > r) { return null; } const mid = (l + r) >> 1; return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); }; return dfs(0, nums.length - 1); };
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: def dfs(l: int, r: int) -> Optional[TreeNode]: if l > r: return None mid = (l + r) >> 1 return TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)) return dfs(0, len(nums) - 1)
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { fn dfs(nums: &Vec<i32>, l: usize, r: usize) -> Option<Rc<RefCell<TreeNode>>> { if l > r { return None; } let mid = (l + r) / 2; if mid >= nums.len() { return None; } let mut node = Rc::new(RefCell::new(TreeNode::new(nums[mid]))); node.borrow_mut().left = dfs(nums, l, mid - 1); node.borrow_mut().right = dfs(nums, mid + 1, r); Some(node) } dfs(&nums, 0, nums.len() - 1) } }
108
Convert Sorted Array to Binary Search Tree
Easy
<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree1.jpg" style="width: 302px; height: 222px;" /> <pre> <strong>Input:</strong> nums = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted: <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree2.jpg" style="width: 302px; height: 222px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/images/btree.jpg" style="width: 342px; height: 142px;" /> <pre> <strong>Input:</strong> nums = [1,3] <strong>Output:</strong> [3,1] <strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li> </ul>
Tree; Binary Search Tree; Array; Divide and Conquer; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function sortedArrayToBST(nums: number[]): TreeNode | null { const dfs = (l: number, r: number): TreeNode | null => { if (l > r) { return null; } const mid = (l + r) >> 1; return new TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r)); }; return dfs(0, nums.length - 1); }
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* dfs(int* nums, int i, int j) { if (i > j) { return NULL; } int mid = (i + j) >> 1; struct TreeNode* left = dfs(nums, i, mid - 1); struct TreeNode* right = dfs(nums, mid + 1, j); struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode)); root->val = nums[mid]; root->left = left; root->right = right; return root; } struct TreeNode* sortedListToBST(struct ListNode* head) { int size = 0; struct ListNode* temp = head; while (temp) { size++; temp = temp->next; } int* nums = (int*) malloc(size * sizeof(int)); temp = head; for (int i = 0; i < size; i++) { nums[i] = temp->val; temp = temp->next; } struct TreeNode* root = dfs(nums, 0, size - 1); free(nums); return root; }
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * 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: TreeNode* sortedListToBST(ListNode* head) { vector<int> nums; for (; head; head = head->next) { nums.push_back(head->val); } auto dfs = [&](this auto&& dfs, int i, int j) -> TreeNode* { if (i > j) { return nullptr; } int mid = (i + j) >> 1; TreeNode* left = dfs(i, mid - 1); TreeNode* right = dfs(mid + 1, j); return new TreeNode(nums[mid], left, right); }; return dfs(0, nums.size() - 1); } };
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sortedListToBST(head *ListNode) *TreeNode { nums := []int{} for ; head != nil; head = head.Next { nums = append(nums, head.Val) } var dfs func(i, j int) *TreeNode dfs = func(i, j int) *TreeNode { if i > j { return nil } mid := (i + j) >> 1 left := dfs(i, mid-1) right := dfs(mid+1, j) return &TreeNode{nums[mid], left, right} } return dfs(0, len(nums)-1) }
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private List<Integer> nums = new ArrayList<>(); public TreeNode sortedListToBST(ListNode head) { for (; head != null; head = head.next) { nums.add(head.val); } return dfs(0, nums.size() - 1); } private TreeNode dfs(int i, int j) { if (i > j) { return null; } int mid = (i + j) >> 1; TreeNode left = dfs(i, mid - 1); TreeNode right = dfs(mid + 1, j); return new TreeNode(nums.get(mid), left, right); } }
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {ListNode} head * @return {TreeNode} */ var sortedListToBST = function (head) { const nums = []; for (; head; head = head.next) { nums.push(head.val); } const dfs = (i, j) => { if (i > j) { return null; } const mid = (i + j) >> 1; const left = dfs(i, mid - 1); const right = dfs(mid + 1, j); return new TreeNode(nums[mid], left, right); }; return dfs(0, nums.length - 1); };
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: def dfs(i: int, j: int) -> Optional[TreeNode]: if i > j: return None mid = (i + j) >> 1 l, r = dfs(i, mid - 1), dfs(mid + 1, j) return TreeNode(nums[mid], l, r) nums = [] while head: nums.append(head.val) head = head.next return dfs(0, len(nums) - 1)
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn sorted_list_to_bst(head: Option<Box<ListNode>>) -> Option<Rc<RefCell<TreeNode>>> { let mut nums = Vec::new(); let mut current = head; while let Some(node) = current { nums.push(node.val); current = node.next; } fn dfs(nums: &[i32]) -> Option<Rc<RefCell<TreeNode>>> { if nums.is_empty() { return None; } let mid = nums.len() / 2; Some(Rc::new(RefCell::new(TreeNode { val: nums[mid], left: dfs(&nums[..mid]), right: dfs(&nums[mid + 1..]), }))) } dfs(&nums) } }
109
Convert Sorted List to Binary Search Tree
Medium
<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword="height-balanced"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/images/linked.jpg" style="width: 500px; height: 388px;" /> <pre> <strong>Input:</strong> head = [-10,-3,0,5,9] <strong>Output:</strong> [0,-3,9,-10,null,5] <strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> </ul>
Tree; Binary Search Tree; Linked List; Divide and Conquer; Binary Tree
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ /** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function sortedListToBST(head: ListNode | null): TreeNode | null { const nums: number[] = []; for (; head; head = head.next) { nums.push(head.val); } const dfs = (i: number, j: number): TreeNode | null => { if (i > j) { return null; } const mid = (i + j) >> 1; const left = dfs(i, mid - 1); const right = dfs(mid + 1, j); return new TreeNode(nums[mid], left, right); }; return dfs(0, nums.length - 1); }
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * 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: bool isBalanced(TreeNode* root) { function<int(TreeNode*)> height = [&](TreeNode* root) { if (!root) { return 0; } int l = height(root->left); int r = height(root->right); if (l == -1 || r == -1 || abs(l - r) > 1) { return -1; } return 1 + max(l, r); }; return height(root) >= 0; } };
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isBalanced(root *TreeNode) bool { var height func(*TreeNode) int height = func(root *TreeNode) int { if root == nil { return 0 } l, r := height(root.Left), height(root.Right) if l == -1 || r == -1 || abs(l-r) > 1 { return -1 } if l > r { return 1 + l } return 1 + r } return height(root) >= 0 } func abs(x int) int { if x < 0 { return -x } return x }
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isBalanced(TreeNode root) { return height(root) >= 0; } private int height(TreeNode root) { if (root == null) { return 0; } int l = height(root.left); int r = height(root.right); if (l == -1 || r == -1 || Math.abs(l - r) > 1) { return -1; } return 1 + Math.max(l, r); } }
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ var isBalanced = function (root) { const height = root => { if (!root) { return 0; } const l = height(root.left); const r = height(root.right); if (l == -1 || r == -1 || Math.abs(l - r) > 1) { return -1; } return 1 + Math.max(l, r); }; return height(root) >= 0; };
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: def height(root): if root is None: return 0 l, r = height(root.left), height(root.right) if l == -1 or r == -1 or abs(l - r) > 1: return -1 return 1 + max(l, r) return height(root) >= 0
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool { Self::dfs(&root) > -1 } fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 { if root.is_none() { return 0; } let node = root.as_ref().unwrap().borrow(); let left = Self::dfs(&node.left); let right = Self::dfs(&node.right); if left == -1 || right == -1 || (left - right).abs() > 1 { return -1; } 1 + left.max(right) } }
110
Balanced Binary Tree
Easy
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_1.jpg" style="width: 342px; height: 221px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0110.Balanced%20Binary%20Tree/images/balance_2.jpg" style="width: 452px; height: 301px;" /> <pre> <strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4] <strong>Output:</strong> false </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul>
Tree; Depth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function isBalanced(root: TreeNode | null): boolean { const dfs = (root: TreeNode | null) => { if (root == null) { return 0; } const left = dfs(root.left); const right = dfs(root.right); if (left === -1 || right === -1 || Math.abs(left - right) > 1) { return -1; } return 1 + Math.max(left, right); }; return dfs(root) > -1; }
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #define min(a, b) (((a) < (b)) ? (a) : (b)) int minDepth(struct TreeNode* root) { if (!root) { return 0; } if (!root->left) { return 1 + minDepth(root->right); } if (!root->right) { return 1 + minDepth(root->left); } int left = minDepth(root->left); int right = minDepth(root->right); return 1 + min(left, right); }
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * 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: int minDepth(TreeNode* root) { if (!root) { return 0; } if (!root->left) { return 1 + minDepth(root->right); } if (!root->right) { return 1 + minDepth(root->left); } return 1 + min(minDepth(root->left), minDepth(root->right)); } };
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func minDepth(root *TreeNode) int { if root == nil { return 0 } if root.Left == nil { return 1 + minDepth(root.Right) } if root.Right == nil { return 1 + minDepth(root.Left) } return 1 + min(minDepth(root.Left), minDepth(root.Right)) }
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } if (root.left == null) { return 1 + minDepth(root.right); } if (root.right == null) { return 1 + minDepth(root.left); } return 1 + Math.min(minDepth(root.left), minDepth(root.right)); } }
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var minDepth = function (root) { if (!root) { return 0; } if (!root.left) { return 1 + minDepth(root.right); } if (!root.right) { return 1 + minDepth(root.left); } return 1 + Math.min(minDepth(root.left), minDepth(root.right)); };
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 if root.left is None: return 1 + self.minDepth(root.right) if root.right is None: return 1 + self.minDepth(root.left) return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 { if root.is_none() { return 0; } let node = root.as_ref().unwrap().borrow(); if node.left.is_none() { return 1 + Self::dfs(&node.right); } if node.right.is_none() { return 1 + Self::dfs(&node.left); } 1 + Self::dfs(&node.left).min(Self::dfs(&node.right)) } pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { Self::dfs(&root) } }
111
Minimum Depth of Binary Tree
Easy
<p>Given a binary tree, find its minimum depth.</p> <p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p> <p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/images/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>Input:</strong> root = [3,9,20,null,null,15,7] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6] <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function minDepth(root: TreeNode | null): number { if (root == null) { return 0; } const { left, right } = root; if (left == null) { return 1 + minDepth(right); } if (right == null) { return 1 + minDepth(left); } return 1 + Math.min(minDepth(left), minDepth(right)); }
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * 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: bool hasPathSum(TreeNode* root, int targetSum) { function<bool(TreeNode*, int)> dfs = [&](TreeNode* root, int s) -> int { if (!root) return false; s += root->val; if (!root->left && !root->right && s == targetSum) return true; return dfs(root->left, s) || dfs(root->right, s); }; return dfs(root, 0); } };
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func hasPathSum(root *TreeNode, targetSum int) bool { var dfs func(*TreeNode, int) bool dfs = func(root *TreeNode, s int) bool { if root == nil { return false } s += root.Val if root.Left == nil && root.Right == nil && s == targetSum { return true } return dfs(root.Left, s) || dfs(root.Right, s) } return dfs(root, 0) }
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { return dfs(root, targetSum); } private boolean dfs(TreeNode root, int s) { if (root == null) { return false; } s -= root.val; if (root.left == null && root.right == null && s == 0) { return true; } return dfs(root.left, s) || dfs(root.right, s); } }
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {boolean} */ var hasPathSum = function (root, targetSum) { function dfs(root, s) { if (!root) return false; s += root.val; if (!root.left && !root.right && s == targetSum) return true; return dfs(root.left, s) || dfs(root.right, s); } return dfs(root, 0); };
112
Path Sum
Easy
<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p> <p>A <strong>leaf</strong> is a node with no children.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum1.jpg" style="width: 500px; height: 356px;" /> <pre> <strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 <strong>Output:</strong> true <strong>Explanation:</strong> The root-to-leaf path with the target sum is shown. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0112.Path%20Sum/images/pathsum2.jpg" /> <pre> <strong>Input:</strong> root = [1,2,3], targetSum = 5 <strong>Output:</strong> false <strong>Explanation:</strong> There are two root-to-leaf paths in the tree: (1 --&gt; 2): The sum is 3. (1 --&gt; 3): The sum is 4. There is no root-to-leaf path with sum = 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], targetSum = 0 <strong>Output:</strong> false <strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li> <li><code>-1000 &lt;= Node.val &lt;= 1000</code></li> <li><code>-1000 &lt;= targetSum &lt;= 1000</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: def dfs(root, s): if root is None: return False s += root.val if root.left is None and root.right is None and s == targetSum: return True return dfs(root.left, s) or dfs(root.right, s) return dfs(root, 0)