码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-01-30 09:37:00      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

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;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5170462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!