Flatten Binary Tree to Linked List
来源:互联网 发布:pstn网络 编辑:程序博客网 时间:2024/05/29 03:16
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
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private: TreeNode *last;//保存上一次访问的叶子节点,也就是list的尾节点public: void flatten(TreeNode *root) { last=NULL; flat(root); } void flat(TreeNode *root){ if(!root) return; if(!root->left&&!root->right){ last=root; return; } if(!root->left){ flat(root->right); return; } if(!root->right){ root->right=root->left; root->left=NULL;//important flat(root->right); return; } TreeNode *r = root->right; root->right=root->left; root->left=NULL;//important flat(root->right); last->left=NULL; last->right=r;//连接起来 flat(r); } };
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
- 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
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- codeforces 417D Cunning Gena
- android拍照压缩及添加水印3
- oracle 数据类型详解---日期型
- CF31D 分治
- 1010. Radix (25)
- Flatten Binary Tree to Linked List
- Swift中的!和?
- 1011. World Cup Betting (20)
- SQL Server不区分大小写的问题
- 图像处理+机器学习相关资源整合
- PHP关闭notice级别的错误提示
- 1012. The Best Rank (25)
- Handler消息传递机制(三)管理MessageQueue的Looper
- Android截屏方法