LeetCode @ Tree – Flatten Binary Tree to Linked List

来源:互联网 发布:我的世界飞机手机版js 编辑:程序博客网 时间:2024/06/10 15:33

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

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */// 做关于tree的题目,一定要联想到 tree 的三种遍历 及其方法: 前序,中序, 后序。 无外乎用这三种方法来解题。//方法一: 借助一个Helper function, 让其可以返回一个TreeNode, 便于后续的recursion 操作。(In-place) /* 写 recursion 时需要注意的地方:   1. 一定要有跳出条件 (初始条件)。   2. 写出recursion: tree来说就是 a = rec(root.right) , b = rec(root.left); list来说就是 c = rec(list.next)(即下一步)   3. 写出处理当前情况的function。   4. 注意返回条件。*/public class Solution {    public void flatten(TreeNode root) {       Helper(root);    }    private TreeNode Helper(TreeNode root) {       if (root == null) {      // 跳出条件一定要有           return root;       }       TreeNode right = Helper(root.right);       TreeNode left = Helper(root.left);       root.left = null;       if (left != null) {           root.right = left;           TreeNode cur = left;    // cur一定要有。            while (cur.right != null) { //cur.right != null, cur走到最后一个点; 如果,cur != NULL , cur最后是null               cur = cur.right;           }           cur.right = right;       } else {           root.right = right;       }        return root;           }}// 方法二: 利用stack , 由于题目本身是 前序遍历, 可以利用前序遍历的 iteration 方式来做。 public class Solution {    public void flatten(TreeNode root) {        H(root);    }    private TreeNode H(TreeNode root) {          if (root == null) {            return null;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        stack.push(root);        TreeNode dummy = new TreeNode(0);        dummy.left = null;        TreeNode cur = dummy;        while (!stack.empty()) {            cur.right = stack.pop();            cur = cur.right;                        if (cur.right != null) {                stack.push(cur.right);            }            if (cur.left != null) {                stack.push(cur.left);            }            cur.left = null;        }        return dummy.right;    }  }


0 0
原创粉丝点击