标签:pre point highlight code flat linked list like 分治
Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / 2 5 / \ 3 4 6 The flattened tree should look like: 1 2 3 4 5 6 click to show hints. Hints: If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
树的题首先找容器(是全局变量还是输入值的递归 ), 再确定是分治(多后序) 还是递归(多前序),确定递归出口: 是否需要是找叶节点(left && right == null) 作正常出口(此时是输入值的递归见 257. Binary Tree Paths), 是否需要改变树的结构(此题借助pre改变左子树和上层节点作为右子树), 是否借助树的深度? 返回值是否为结果值, 或结果值作为全局变量, 返回中间值(见563 Binary Tree Tilt) 等等都是树的小知识加上容器, 加上先序? 后序? 中间值的做法.
public class Solution { TreeNode pre = null; public void flatten(TreeNode root) { if (root == null) { return; } helper(root); } private void helper(TreeNode root) { if (root == null) { return; } if (pre != null) { pre.left = null; pre.right = root; } pre = root; TreeNode right = root.right; helper(root.left); //} //if (right != null) { helper(right); //} } }
if (root == null) { return; } // 有了这句不用在判断左右是否为空再递归 : if (right != null) {
用先序遍历借助额外点即上层的点递的时候改变树的结构, 然后尾递归直接返回
114. Flatten Binary Tree to Linked List
标签:pre point highlight code flat linked list like 分治
原文地址:http://www.cnblogs.com/apanda009/p/7267921.html