`
blue2048
  • 浏览: 183072 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Flatten Binary Tree to Linked List - java 先序遍历

阅读更多
/**

 * 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;

        }

        List<TreeNode> nodeList = new ArrayList<TreeNode>();

        f(root, nodeList);

        TreeNode pre = null;

        for(TreeNode node : nodeList){

            if(pre != null){

                pre.left=null;

                pre.right=node;

            }

            pre = node;

        }

    }



    private void f(TreeNode node, List<TreeNode> nodeList){

        nodeList.add(node);

        if(node.left != null){

            f(node.left, nodeList);

        }

        if(node.right!=null){

            f(node.right, nodeList);

        }

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics