Flatten Binary Tree to Linked List

来源:互联网 发布:上海淘宝运营培训班 编辑:程序博客网 时间:2024/06/06 05:06

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.

Have you been asked this question in an interview?

这道题目用stack 或者recursive 实现 preorder traversal
有一个小细节要注意,就是在对每个TreeNode 处理的时候,要记得把他们的左结点设为null

/** * Definition for binary tree * 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> st = new Stack<TreeNode>();        st.push(root);        TreeNode cur;        TreeNode dummy = new TreeNode(0);        TreeNode pre = dummy;        while (!st.empty()) {            cur = st.pop();            if (cur.right != null) {                st.push(cur.right);            } if (cur.left != null) {                st.push(cur.left);            }            cur.left = null;            pre.right = cur;            pre = pre.right;        }    }}



0 0