LeetCode 热题100-44-二叉树展开为链表

核心思路:前序遍历
思路:
边前序遍历,边重构边信息(借助pre指针)。
不喜欢递归版本,太简单,所以没写。
注意点:
重构树结构时,记得把左子树指向null。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if(root == null){
            return ;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);
        TreeNode pre = null;
        while(!deque.isEmpty()){
            TreeNode t = deque.pollLast();
            if(pre != null){
                pre.left = null;
                pre.right = t;
            }
            TreeNode left = t.left;
            TreeNode right = t.right;
            if(right != null){
                deque.addLast(right);
            }
            if(left != null){
                deque.addLast(left);
            }
            pre = t;
        }
    }
}

你可能感兴趣的:(Leetcode热题100,leetcode,java)