diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/README.md b/solution/0100-0199/0199.Binary Tree Right Side View/README.md index da6be6a7b99fb..29743be261d0f 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/README.md +++ b/solution/0100-0199/0199.Binary Tree Right Side View/README.md @@ -80,7 +80,7 @@ tags: ### 方法一:BFS -使用 BFS 层序遍历二叉树,每层最后一个节点即为该层的右视图节点。 +我们可以使用广度优先搜索,定义一个队列 $\textit{q}$,将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。 @@ -102,13 +102,13 @@ class Solution: return ans q = deque([root]) while q: - ans.append(q[-1].val) + ans.append(q[0].val) for _ in range(len(q)): node = q.popleft() - if node.left: - q.append(node.left) if node.right: q.append(node.right) + if node.left: + q.append(node.left) return ans ``` @@ -139,15 +139,15 @@ class Solution { Deque q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { - ans.add(q.peekLast().val); - for (int n = q.size(); n > 0; --n) { + ans.add(q.peekFirst().val); + for (int k = q.size(); k > 0; --k) { TreeNode node = q.poll(); - if (node.left != null) { - q.offer(node.left); - } if (node.right != null) { q.offer(node.right); } + if (node.left != null) { + q.offer(node.left); + } } } return ans; @@ -177,17 +177,17 @@ public: return ans; } queue q{{root}}; - while (!q.empty()) { - ans.emplace_back(q.back()->val); - for (int n = q.size(); n; --n) { - TreeNode* node = q.front(); + while (q.size()) { + ans.push_back(q.front()->val); + for (int k = q.size(); k; --k) { + auto node = q.front(); q.pop(); - if (node->left) { - q.push(node->left); - } if (node->right) { q.push(node->right); } + if (node->left) { + q.push(node->left); + } } } return ans; @@ -212,16 +212,16 @@ func rightSideView(root *TreeNode) (ans []int) { } q := []*TreeNode{root} for len(q) > 0 { - ans = append(ans, q[len(q)-1].Val) - for n := len(q); n > 0; n-- { + ans = append(ans, q[0].Val) + for k := len(q); k > 0; k-- { node := q[0] q = q[1:] - if node.Left != nil { - q = append(q, node.Left) - } if node.Right != nil { q = append(q, node.Right) } + if node.Left != nil { + q = append(q, node.Left) + } } } return @@ -246,23 +246,24 @@ func rightSideView(root *TreeNode) (ans []int) { */ function rightSideView(root: TreeNode | null): number[] { + const ans: number[] = []; if (!root) { - return []; + return ans; } - let q = [root]; - const ans: number[] = []; - while (q.length) { - const nextq: TreeNode[] = []; - ans.push(q.at(-1)!.val); + const q: TreeNode[] = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq: TreeNode[] = []; for (const { left, right } of q) { - if (left) { - nextq.push(left); - } if (right) { - nextq.push(right); + nq.push(right); + } + if (left) { + nq.push(left); } } - q = nextq; + q.length = 0; + q.push(...nq); } return ans; } @@ -294,32 +295,71 @@ use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option>>) -> Vec { - let mut res = vec![]; + let mut ans = vec![]; if root.is_none() { - return res; + return ans; } let mut q = VecDeque::new(); q.push_back(root); while !q.is_empty() { - let n = q.len(); - res.push(q[n - 1].as_ref().unwrap().borrow().val); - for _ in 0..n { + let k = q.len(); + ans.push(q[0].as_ref().unwrap().borrow().val); + for _ in 0..k { if let Some(node) = q.pop_front().unwrap() { let mut node = node.borrow_mut(); - if node.left.is_some() { - q.push_back(node.left.take()); - } if node.right.is_some() { q.push_back(node.right.take()); } + if node.left.is_some() { + q.push_back(node.left.take()); + } } } } - res + ans } } ``` +#### JavaScript + +```js +/** + * 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 rightSideView = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq = []; + for (const { left, right } of q) { + if (right) { + nq.push(right); + } + if (left) { + nq.push(left); + } + } + q.length = 0; + q.push(...nq); + } + return ans; +}; +``` + @@ -345,13 +385,13 @@ impl Solution { # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: - def dfs(node, depth): - if node is None: + def dfs(root: Optional[TreeNode], depth: int) -> None: + if root is None: return - if depth == len(ans): - ans.append(node.val) - dfs(node.right, depth + 1) - dfs(node.left, depth + 1) + if len(ans) == depth: + ans.append(root.val) + dfs(root.right, depth + 1) + dfs(root.left, depth + 1) ans = [] dfs(root, 0) @@ -384,15 +424,15 @@ class Solution { return ans; } - private void dfs(TreeNode node, int depth) { - if (node == null) { + private void dfs(TreeNode root, int depth) { + if (root == null) { return; } - if (depth == ans.size()) { - ans.add(node.val); + if (ans.size() == depth) { + ans.add(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); } } ``` @@ -415,15 +455,15 @@ class Solution { public: vector rightSideView(TreeNode* root) { vector ans; - function dfs = [&](TreeNode* node, int depth) { - if (!node) { + auto dfs = [&](this auto&& dfs, TreeNode* root, int depth) -> void { + if (!root) { return; } - if (depth == ans.size()) { - ans.emplace_back(node->val); + if (ans.size() == depth) { + ans.push_back(root->val); } - dfs(node->right, depth + 1); - dfs(node->left, depth + 1); + dfs(root->right, depth + 1); + dfs(root->left, depth + 1); }; dfs(root, 0); return ans; @@ -444,15 +484,15 @@ public: */ func rightSideView(root *TreeNode) (ans []int) { var dfs func(*TreeNode, int) - dfs = func(node *TreeNode, depth int) { - if node == nil { + dfs = func(root *TreeNode, depth int) { + if root == nil { return } - if depth == len(ans) { - ans = append(ans, node.Val) + if len(ans) == depth { + ans = append(ans, root.Val) } - dfs(node.Right, depth+1) - dfs(node.Left, depth+1) + dfs(root.Right, depth+1) + dfs(root.Left, depth+1) } dfs(root, 0) return @@ -478,21 +518,95 @@ func rightSideView(root *TreeNode) (ans []int) { function rightSideView(root: TreeNode | null): number[] { const ans = []; - const dfs = (node: TreeNode | null, depth: number) => { - if (!node) { + const dfs = (root: TreeNode | null, depth: number) => { + if (!root) { return; } - if (depth == ans.length) { - ans.push(node.val); + if (ans.length == depth) { + ans.push(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); }; dfs(root, 0); return ans; } ``` +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// 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 right_side_view(root: Option>>) -> Vec { + let mut ans = Vec::new(); + fn dfs(node: Option>>, depth: usize, ans: &mut Vec) { + if let Some(node_ref) = node { + let node = node_ref.borrow(); + if ans.len() == depth { + ans.push(node.val); + } + dfs(node.right.clone(), depth + 1, ans); + dfs(node.left.clone(), depth + 1, ans); + } + } + dfs(root, 0, &mut ans); + ans + } +} +``` + +#### JavaScript + +```js +/** + * 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 rightSideView = function (root) { + const ans = []; + const dfs = (root, depth) => { + if (!root) { + return; + } + if (ans.length == depth) { + ans.push(root.val); + } + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); + }; + dfs(root, 0); + return ans; +}; +``` + diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md b/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md index a0cd82a993920..ce9d86092bb2d 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md +++ b/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md @@ -76,7 +76,11 @@ tags: -### Solution 1 +### Solution 1: BFS + +We can use breadth-first search (BFS) and define a queue $\textit{q}$ to store the nodes. We start by putting the root node into the queue. Each time, we take out all the nodes of the current level from the queue. For the current node, we first check if the right subtree exists; if it does, we put the right subtree into the queue. Then, we check if the left subtree exists; if it does, we put the left subtree into the queue. This way, the first node taken out from the queue each time is the rightmost node of that level. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. @@ -96,13 +100,13 @@ class Solution: return ans q = deque([root]) while q: - ans.append(q[-1].val) + ans.append(q[0].val) for _ in range(len(q)): node = q.popleft() - if node.left: - q.append(node.left) if node.right: q.append(node.right) + if node.left: + q.append(node.left) return ans ``` @@ -133,15 +137,15 @@ class Solution { Deque q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { - ans.add(q.peekLast().val); - for (int n = q.size(); n > 0; --n) { + ans.add(q.peekFirst().val); + for (int k = q.size(); k > 0; --k) { TreeNode node = q.poll(); - if (node.left != null) { - q.offer(node.left); - } if (node.right != null) { q.offer(node.right); } + if (node.left != null) { + q.offer(node.left); + } } } return ans; @@ -171,17 +175,17 @@ public: return ans; } queue q{{root}}; - while (!q.empty()) { - ans.emplace_back(q.back()->val); - for (int n = q.size(); n; --n) { - TreeNode* node = q.front(); + while (q.size()) { + ans.push_back(q.front()->val); + for (int k = q.size(); k; --k) { + auto node = q.front(); q.pop(); - if (node->left) { - q.push(node->left); - } if (node->right) { q.push(node->right); } + if (node->left) { + q.push(node->left); + } } } return ans; @@ -206,16 +210,16 @@ func rightSideView(root *TreeNode) (ans []int) { } q := []*TreeNode{root} for len(q) > 0 { - ans = append(ans, q[len(q)-1].Val) - for n := len(q); n > 0; n-- { + ans = append(ans, q[0].Val) + for k := len(q); k > 0; k-- { node := q[0] q = q[1:] - if node.Left != nil { - q = append(q, node.Left) - } if node.Right != nil { q = append(q, node.Right) } + if node.Left != nil { + q = append(q, node.Left) + } } } return @@ -240,23 +244,24 @@ func rightSideView(root *TreeNode) (ans []int) { */ function rightSideView(root: TreeNode | null): number[] { + const ans: number[] = []; if (!root) { - return []; + return ans; } - let q = [root]; - const ans: number[] = []; - while (q.length) { - const nextq: TreeNode[] = []; - ans.push(q.at(-1)!.val); + const q: TreeNode[] = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq: TreeNode[] = []; for (const { left, right } of q) { - if (left) { - nextq.push(left); - } if (right) { - nextq.push(right); + nq.push(right); + } + if (left) { + nq.push(left); } } - q = nextq; + q.length = 0; + q.push(...nq); } return ans; } @@ -288,39 +293,82 @@ use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option>>) -> Vec { - let mut res = vec![]; + let mut ans = vec![]; if root.is_none() { - return res; + return ans; } let mut q = VecDeque::new(); q.push_back(root); while !q.is_empty() { - let n = q.len(); - res.push(q[n - 1].as_ref().unwrap().borrow().val); - for _ in 0..n { + let k = q.len(); + ans.push(q[0].as_ref().unwrap().borrow().val); + for _ in 0..k { if let Some(node) = q.pop_front().unwrap() { let mut node = node.borrow_mut(); - if node.left.is_some() { - q.push_back(node.left.take()); - } if node.right.is_some() { q.push_back(node.right.take()); } + if node.left.is_some() { + q.push_back(node.left.take()); + } } } } - res + ans } } ``` +#### JavaScript + +```js +/** + * 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 rightSideView = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq = []; + for (const { left, right } of q) { + if (right) { + nq.push(right); + } + if (left) { + nq.push(left); + } + } + q.length = 0; + q.push(...nq); + } + return ans; +}; +``` + -### Solution 2 +### Solution 2: DFS + +Use DFS (depth-first search) to traverse the binary tree. Each time, traverse the right subtree first, then the left subtree. This way, the first node visited at each level is the rightmost node of that level. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. @@ -335,13 +383,13 @@ impl Solution { # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: - def dfs(node, depth): - if node is None: + def dfs(root: Optional[TreeNode], depth: int) -> None: + if root is None: return - if depth == len(ans): - ans.append(node.val) - dfs(node.right, depth + 1) - dfs(node.left, depth + 1) + if len(ans) == depth: + ans.append(root.val) + dfs(root.right, depth + 1) + dfs(root.left, depth + 1) ans = [] dfs(root, 0) @@ -374,15 +422,15 @@ class Solution { return ans; } - private void dfs(TreeNode node, int depth) { - if (node == null) { + private void dfs(TreeNode root, int depth) { + if (root == null) { return; } - if (depth == ans.size()) { - ans.add(node.val); + if (ans.size() == depth) { + ans.add(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); } } ``` @@ -405,15 +453,15 @@ class Solution { public: vector rightSideView(TreeNode* root) { vector ans; - function dfs = [&](TreeNode* node, int depth) { - if (!node) { + auto dfs = [&](this auto&& dfs, TreeNode* root, int depth) -> void { + if (!root) { return; } - if (depth == ans.size()) { - ans.emplace_back(node->val); + if (ans.size() == depth) { + ans.push_back(root->val); } - dfs(node->right, depth + 1); - dfs(node->left, depth + 1); + dfs(root->right, depth + 1); + dfs(root->left, depth + 1); }; dfs(root, 0); return ans; @@ -434,15 +482,15 @@ public: */ func rightSideView(root *TreeNode) (ans []int) { var dfs func(*TreeNode, int) - dfs = func(node *TreeNode, depth int) { - if node == nil { + dfs = func(root *TreeNode, depth int) { + if root == nil { return } - if depth == len(ans) { - ans = append(ans, node.Val) + if len(ans) == depth { + ans = append(ans, root.Val) } - dfs(node.Right, depth+1) - dfs(node.Left, depth+1) + dfs(root.Right, depth+1) + dfs(root.Left, depth+1) } dfs(root, 0) return @@ -468,21 +516,127 @@ func rightSideView(root *TreeNode) (ans []int) { function rightSideView(root: TreeNode | null): number[] { const ans = []; - const dfs = (node: TreeNode | null, depth: number) => { - if (!node) { + const dfs = (root: TreeNode | null, depth: number) => { + if (!root) { + return; + } + if (ans.length == depth) { + ans.push(root.val); + } + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); + }; + dfs(root, 0); + return ans; +} +``` + +#### JavaScript + +```js +/** + * 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 rightSideView = function (root) { + const ans = []; + const dfs = (root, depth) => { + if (!root) { return; } - if (depth == ans.length) { - ans.push(node.val); + if (ans.length == depth) { + ans.push(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); }; dfs(root, 0); return ans; +}; +``` + +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// 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 right_side_view(root: Option>>) -> Vec { + let mut ans = Vec::new(); + fn dfs(node: Option>>, depth: usize, ans: &mut Vec) { + if let Some(node_ref) = node { + let node = node_ref.borrow(); + if ans.len() == depth { + ans.push(node.val); + } + dfs(node.right.clone(), depth + 1, ans); + dfs(node.left.clone(), depth + 1, ans); + } + } + dfs(root, 0, &mut ans); + ans + } } ``` +#### JavaScript + +```js +/** + * 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 rightSideView = function (root) { + const ans = []; + const dfs = (root, depth) => { + if (!root) { + return; + } + if (ans.length == depth) { + ans.push(root.val); + } + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); + }; + dfs(root, 0); + return ans; +}; +``` + diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.cpp b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.cpp index c9ce57132dfa4..e3a7f74a713aa 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.cpp +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.cpp @@ -17,19 +17,19 @@ class Solution { return ans; } queue q{{root}}; - while (!q.empty()) { - ans.emplace_back(q.back()->val); - for (int n = q.size(); n; --n) { - TreeNode* node = q.front(); + while (q.size()) { + ans.push_back(q.front()->val); + for (int k = q.size(); k; --k) { + auto node = q.front(); q.pop(); - if (node->left) { - q.push(node->left); - } if (node->right) { q.push(node->right); } + if (node->left) { + q.push(node->left); + } } } return ans; } -}; \ No newline at end of file +}; diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.go b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.go index 60f7cd46dda0b..fbc9e8f06ebf8 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.go +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.go @@ -12,17 +12,17 @@ func rightSideView(root *TreeNode) (ans []int) { } q := []*TreeNode{root} for len(q) > 0 { - ans = append(ans, q[len(q)-1].Val) - for n := len(q); n > 0; n-- { + ans = append(ans, q[0].Val) + for k := len(q); k > 0; k-- { node := q[0] q = q[1:] - if node.Left != nil { - q = append(q, node.Left) - } if node.Right != nil { q = append(q, node.Right) } + if node.Left != nil { + q = append(q, node.Left) + } } } return -} \ No newline at end of file +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.java b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.java index 4a2676e5f93e2..73ef75057155b 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.java +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.java @@ -22,17 +22,17 @@ public List rightSideView(TreeNode root) { Deque q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { - ans.add(q.peekLast().val); - for (int n = q.size(); n > 0; --n) { + ans.add(q.peekFirst().val); + for (int k = q.size(); k > 0; --k) { TreeNode node = q.poll(); - if (node.left != null) { - q.offer(node.left); - } if (node.right != null) { q.offer(node.right); } + if (node.left != null) { + q.offer(node.left); + } } } return ans; } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.js b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.js new file mode 100644 index 0000000000000..b77f284b5eeab --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.js @@ -0,0 +1,34 @@ +/** + * 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 rightSideView = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq = []; + for (const { left, right } of q) { + if (right) { + nq.push(right); + } + if (left) { + nq.push(left); + } + } + q.length = 0; + q.push(...nq); + } + return ans; +}; diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.py b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.py index 164d0991ee717..b03a41d862bc8 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.py +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.py @@ -11,11 +11,11 @@ def rightSideView(self, root: Optional[TreeNode]) -> List[int]: return ans q = deque([root]) while q: - ans.append(q[-1].val) + ans.append(q[0].val) for _ in range(len(q)): node = q.popleft() - if node.left: - q.append(node.left) if node.right: q.append(node.right) + if node.left: + q.append(node.left) return ans diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.rs b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.rs index a92b5c2f5a8a9..56c38a2750835 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.rs +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.rs @@ -21,27 +21,27 @@ use std::collections::VecDeque; use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option>>) -> Vec { - let mut res = vec![]; + let mut ans = vec![]; if root.is_none() { - return res; + return ans; } let mut q = VecDeque::new(); q.push_back(root); while !q.is_empty() { - let n = q.len(); - res.push(q[n - 1].as_ref().unwrap().borrow().val); - for _ in 0..n { + let k = q.len(); + ans.push(q[0].as_ref().unwrap().borrow().val); + for _ in 0..k { if let Some(node) = q.pop_front().unwrap() { let mut node = node.borrow_mut(); - if node.left.is_some() { - q.push_back(node.left.take()); - } if node.right.is_some() { q.push_back(node.right.take()); } + if node.left.is_some() { + q.push_back(node.left.take()); + } } } } - res + ans } } diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.ts b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.ts index 141c538ce8777..00d8770de32e1 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution.ts +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution.ts @@ -13,23 +13,24 @@ */ function rightSideView(root: TreeNode | null): number[] { + const ans: number[] = []; if (!root) { - return []; + return ans; } - let q = [root]; - const ans: number[] = []; - while (q.length) { - const nextq: TreeNode[] = []; - ans.push(q.at(-1)!.val); + const q: TreeNode[] = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq: TreeNode[] = []; for (const { left, right } of q) { - if (left) { - nextq.push(left); - } if (right) { - nextq.push(right); + nq.push(right); + } + if (left) { + nq.push(left); } } - q = nextq; + q.length = 0; + q.push(...nq); } return ans; } diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp index 67808eccccedc..75f03cad44f2f 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.cpp @@ -13,17 +13,17 @@ class Solution { public: vector rightSideView(TreeNode* root) { vector ans; - function dfs = [&](TreeNode* node, int depth) { - if (!node) { + auto dfs = [&](this auto&& dfs, TreeNode* root, int depth) -> void { + if (!root) { return; } - if (depth == ans.size()) { - ans.emplace_back(node->val); + if (ans.size() == depth) { + ans.push_back(root->val); } - dfs(node->right, depth + 1); - dfs(node->left, depth + 1); + dfs(root->right, depth + 1); + dfs(root->left, depth + 1); }; dfs(root, 0); return ans; } -}; \ No newline at end of file +}; diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go index 26827861a38d1..46bcbad5cae01 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.go @@ -8,16 +8,16 @@ */ func rightSideView(root *TreeNode) (ans []int) { var dfs func(*TreeNode, int) - dfs = func(node *TreeNode, depth int) { - if node == nil { + dfs = func(root *TreeNode, depth int) { + if root == nil { return } - if depth == len(ans) { - ans = append(ans, node.Val) + if len(ans) == depth { + ans = append(ans, root.Val) } - dfs(node.Right, depth+1) - dfs(node.Left, depth+1) + dfs(root.Right, depth+1) + dfs(root.Left, depth+1) } dfs(root, 0) return -} \ No newline at end of file +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java index 49e597711858a..0c17514d79fda 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.java @@ -21,14 +21,14 @@ public List rightSideView(TreeNode root) { return ans; } - private void dfs(TreeNode node, int depth) { - if (node == null) { + private void dfs(TreeNode root, int depth) { + if (root == null) { return; } - if (depth == ans.size()) { - ans.add(node.val); + if (ans.size() == depth) { + ans.add(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); } -} \ No newline at end of file +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.js b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.js new file mode 100644 index 0000000000000..fc99de5886f45 --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.js @@ -0,0 +1,27 @@ +/** + * 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 rightSideView = function (root) { + const ans = []; + const dfs = (root, depth) => { + if (!root) { + return; + } + if (ans.length == depth) { + ans.push(root.val); + } + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); + }; + dfs(root, 0); + return ans; +}; diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py index 8680b6976811c..f5e5f5100b783 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.py @@ -6,13 +6,13 @@ # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: - def dfs(node, depth): - if node is None: + def dfs(root: Optional[TreeNode], depth: int) -> None: + if root is None: return - if depth == len(ans): - ans.append(node.val) - dfs(node.right, depth + 1) - dfs(node.left, depth + 1) + if len(ans) == depth: + ans.append(root.val) + dfs(root.right, depth + 1) + dfs(root.left, depth + 1) ans = [] dfs(root, 0) diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.rs b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.rs new file mode 100644 index 0000000000000..ef3567e21c66c --- /dev/null +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.rs @@ -0,0 +1,37 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// 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 right_side_view(root: Option>>) -> Vec { + let mut ans = Vec::new(); + fn dfs(node: Option>>, depth: usize, ans: &mut Vec) { + if let Some(node_ref) = node { + let node = node_ref.borrow(); + if ans.len() == depth { + ans.push(node.val); + } + dfs(node.right.clone(), depth + 1, ans); + dfs(node.left.clone(), depth + 1, ans); + } + } + dfs(root, 0, &mut ans); + ans + } +} diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts index a548d28b05389..aeeed400a0314 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts +++ b/solution/0100-0199/0199.Binary Tree Right Side View/Solution2.ts @@ -14,15 +14,15 @@ function rightSideView(root: TreeNode | null): number[] { const ans = []; - const dfs = (node: TreeNode | null, depth: number) => { - if (!node) { + const dfs = (root: TreeNode | null, depth: number) => { + if (!root) { return; } - if (depth == ans.length) { - ans.push(node.val); + if (ans.length == depth) { + ans.push(root.val); } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); + dfs(root.right, depth + 1); + dfs(root.left, depth + 1); }; dfs(root, 0); return ans;