114. Flatten Binary Tree to ed List
Medium
Given a binary tree, flatten it to a ed list in-place.
For example, given the following tree:
1
/ \\
2 5
/ \\ \\
3 4 6
The flattened tree should look like:
1
\\
2
\\
3
\\
4
\\
5
\\
6
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (null != root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
node.right = stack.isEmpty() ? node.right : stack.peek();
node.left = null;
}
}
}
}
继续阅读与本文标签相同的文章
下一篇 :
社交玩出新花样,脸书为其应用引入专业新闻模块
-
网络基础技术实践#网络安全基础技术实践课程
2026-05-18栏目: 教程
-
阿里云服务器计算网络增强型实例sn1ne 适合中大型网站及性能要求高的公司业务使用
2026-05-18栏目: 教程
-
前端进阶|第八天 京东笔试题,引用传参赋值无效?
2026-05-18栏目: 教程
-
阿里云弹性伸缩ESS必知必会
2026-05-18栏目: 教程
-
MySQL迁移到Cassandra
2026-05-18栏目: 教程
