LeetCode 114 Flatten Binary Tree to Linked List
来源:互联网 发布:养平原巨蜥 知乎 编辑:程序博客网 时间:2024/05/21 17:36
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
public class Solution { public void flatten(TreeNode root) { if(root == null) return ; Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode p = root; stack.add(p); while (!stack.isEmpty()) { p = stack.pop(); if(p.right != null) stack.push(p.right); if(p.left != null) stack.push(p.left); if(p.left==null&&p.right==null){ if(!stack.isEmpty()) p.left=stack.peek(); } } p = root; while(p!=null){ System.out.println(p.val); p=p.left; } while(p!=null){ if(p.left!=null) p.right=p.left; p.left=null; p=p.right; } }}
0 0
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- Leetcode: Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- [Leetcode]Flatten Binary Tree to Linked List
- [leetcode]Flatten Binary Tree to Linked List
- LeetCode-Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode:Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- gets、getc、getchar和getch的区别
- bt 与 ed2k 区别
- linux编译时和运行时,库搜索路径和顺序
- CURL
- 三十分钟掌握STL(2)
- LeetCode 114 Flatten Binary Tree to Linked List
- 适配器模式
- eclipese with gdbserver and Jlink configuration
- Swift初体验(三)
- 三十分钟掌握STL(3)
- Android开发相关工具
- Java学习总结14——JDBC详解
- java 用文件对话框打开文件
- 学习笔记之二叉树的构建