Jan 29 - Flatten Binary Tree To Linked List; DFS;

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 29 - Flatten Binary Tree To Linked List; DFS;相关的知识,希望对你有一定的参考价值。

Using DFS to traverse the tree.

4 cases for each node in the tree:

case 1: it‘s a leaf node, set a pointer pointing to the node. We‘re reaching an end of one dfs search.

case 2: has left child, and no right child, set the right child to be left one, and set left to be null, go into new right child.

case 3: no left child, right child exists. Just go directly into the right child.

case 4: both left and right child exist. First, using dfs to traverse the left subtree, retrieve the former leaf pointer, set its right child to be current node‘s right child. And dfs to traverse the right child one.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode deadend = null;
    public void flatten(TreeNode root) {
        if(root == null) return;
        rotate(root);
        
    }
    
    public void rotate(TreeNode node){
        if(node.left == null && node.right == null) {
            deadend = node;
            return;
        }
        if(node.left != null && node.right == null){
            node.right = node.left;
            node.left = null;
            rotate(node.right);
        }
        else if(node.left == null && node.right != null) rotate(node.right);
        else{
            TreeNode temp = node.right;
            node.right = node.left;
            node.left = null;
            rotate(node.right);
            //System.out.println(deadend.val);
            deadend.right = temp;
            rotate(deadend.right);
        }
    }
    
    /*
    public TreeNode rotate(TreeNode node){
        TreeNode deadend = node;
        TreeNode temp = node.right;
        
        if(node.left != null){
            node.right = node.left;
            deadend = rotate(node.left);
            node.left = null;
            
        }
        if(node.right != null){
            deadend.right = temp;
            deadend = rotate(node.right);
        }
        return deadend;
    }
    */
    
}

 

以上是关于Jan 29 - Flatten Binary Tree To Linked List; DFS;的主要内容,如果未能解决你的问题,请参考以下文章

114. Flatten Binary Tree to Linked List

树Flatten Binary Tree to Linked List(先序遍历)

114. Flatten Binary Tree to Linked List(Medium)

Jan 27 - Valid Binary Search Tree; DFS;

leetcode第一刷_ Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List