LeetCode 114 Flatten Binary Tree to Linked List

来源:互联网 发布:养平原巨蜥 知乎 编辑:程序博客网 时间:2024/05/21 17:36

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
Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

public class Solution {    public void flatten(TreeNode root) {        if(root == null) return ;            Stack<TreeNode> stack=new Stack<TreeNode>();        TreeNode p = root;        stack.add(p);        while (!stack.isEmpty()) {            p = stack.pop();            if(p.right != null)                stack.push(p.right);            if(p.left != null)                stack.push(p.left);            if(p.left==null&&p.right==null){            if(!stack.isEmpty())                p.left=stack.peek();            }        }        p = root;        while(p!=null){        System.out.println(p.val);        p=p.left;        }        while(p!=null){        if(p.left!=null) p.right=p.left;        p.left=null;        p=p.right;        }    }}


0 0
原创粉丝点击