LeetCode Flatten Binary Tree to Linked List
2015-09-09 08:03
423 查看
原题链接在这里:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Method 1: 前序遍历,都加到List里,最后从List加到树里。Time O(n), Space O(n).
Method 2: 在做Pre-order时更改树的结构,使用stack特性,每次出栈时加到lastVisit的右子点,同时更新lastVisit点。
Note: root是不加到任何点的右子点的,所以要加一个限定条件,建立lastVisited = null, 检查lastVisit不为空时才加出栈点到右子,否则跳过,之后才对lastVisited做第一次赋值。
AC Java:
Method 1: 前序遍历,都加到List里,最后从List加到树里。Time O(n), Space O(n).
Method 2: 在做Pre-order时更改树的结构,使用stack特性,每次出栈时加到lastVisit的右子点,同时更新lastVisit点。
Note: root是不加到任何点的右子点的,所以要加一个限定条件,建立lastVisited = null, 检查lastVisit不为空时才加出栈点到右子,否则跳过,之后才对lastVisited做第一次赋值。
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void flatten(TreeNode root) { /* //Method 1 List<Integer> ls = new ArrayList<Integer>(); preOrder(root,ls); int size = ls.size(); TreeNode cur = root; for(int i = 1; i<size; i++){ cur.left = null; cur.right = new TreeNode(ls.get(i)); cur = cur.right; } } private void preOrder(TreeNode root, List<Integer> ls){ if(root == null){ return; } ls.add(root.val); if(root.left != null){ preOrder(root.left, ls); } if(root.right != null){ preOrder(root.right, ls); } } */ //Method 2 if(root == null){ return; } Stack<TreeNode> stk = new Stack<TreeNode>(); stk.push(root); TreeNode lastVisited = null; while(!stk.empty()){ TreeNode tn = stk.pop(); if(lastVisited != null){ lastVisited.left = null; lastVisited.right = tn; } lastVisited = tn; if(tn.right != null){ stk.push(tn.right); } if(tn.left != null){ stk.push(tn.left); } } } }
相关文章推荐
- LeetCode Flatten Binary Tree to Linked List
- shell 脚本中 命令
- Leet Code 9 Palindrome Number
- 2015-9-9
- ios-音频播放-短视频加载-封装工具类
- 私人通讯录(自己也做了一份,但是转载的这个主要是总结的比较到位)
- First Bad Version
- 自定义View-----汽泡效果
- Find Minimum in Rotated Sorted Array II
- poj 1008 Maya Calendar
- BZOJ 1502 [NOI2005]月下柠檬树 自适应Simpson积分
- MogileFS系统简单配置实例
- GHOSTXPSP3电脑爱好者V9.9美化修正版
- ps知识总结
- Find Minimum in Rotated Sorted Array
- 安卓四大组件学习之Service
- UVa 661 - Blowing Fuses
- view.scrollto
- 东邪西毒经典台词
- Leetcode Implement Queue using Stacks