[LeetCode]--114. Flatten Binary Tree to Linked List

来源:互联网 发布:网络在线教育平台 编辑:程序博客网 时间:2024/06/17 12:59

See the problem! LeetCode_114_Flatten_Binary_Tree
Attention--Hints
What’s more, keep in mind the requirement that flatten it to a linked list in place
See the answer code.

/** * 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) {        if (root == null) return;        Stack<TreeNode> stack = new Stack<TreeNode>();        stack.push(root);        while (!stack.isEmpty()) {            TreeNode cur = stack.pop();            if (cur.right != null) stack.push(cur.right);            if (cur.left != null) stack.push(cur.left);            if (!stack.isEmpty()) cur.right = stack.peek();`这里写代码片`            cur.left = null;        }    }}

More important, don’t forget cur.left = null,or you’ll get TLE

Reference:cbmbbz

0 0
原创粉丝点击