LeetCode-114. Flatten Binary Tree to Linked List

来源:互联网 发布:冷艳锯 知乎 编辑:程序博客网 时间:2024/06/05 14:34

题目描述

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

解题思路

采用递归的方式求解,对于每一个节点root,保存该节点的右节点到临时变量,对左右节点分别递归调用。先处理左节点,并将处理的结果作为该root节点的右节点(这就是前面为什么保存右节点的原因),然后找到当root节点的右节点的尾部tmp,处理右节点,并将结果作为tmp的右节点,最后返回root节点。

代码

/** * 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(root == null)            return;        root = flatternCore(root);        // Queue<TreeNode> queue = new LinkedList<TreeNode>();        // while()    }    private TreeNode flatternCore(TreeNode root){        TreeNode right = root.right;        root.right = null;//必须清空右节点,如果左节点不为空会将右节点覆盖,但是如果左节点为空,则会在计算root的右节点时出问题。        if(root.left != null){            root.right = flatternCore(root.left);            root.left = null;        }        if(right != null){            TreeNode tmp = root;            while(tmp.right != null){                tmp=tmp.right;            }            tmp.right=flatternCore(right);        }        return root;    }}
原创粉丝点击