IncredibleThings

导航

LeetCode - Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6
The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        helper(root, stack);
    }
    
    public void helper(TreeNode node, Stack<TreeNode> stack) {
        if (node == null) {
            return;
        }
        if (node.right != null){
            stack.push(node.right);
        }
        if (node.left != null){
            node.right = node.left;
            node.left = null;
        }
        else if(!stack.isEmpty()){
            
            node.right = stack.pop();
        }
        helper(node.right, stack);
    }
}

 

posted on 2020-04-24 13:42  IncredibleThings  阅读(86)  评论(0)    收藏  举报