美文网首页
114. 二叉树展开为链表

114. 二叉树展开为链表

作者: 编程小王子AAA | 来源:发表于2020-04-24 22:22 被阅读0次

二叉树展开为链表
给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6
将其展开为:

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) {
        while(root!=null){
            if(root.left==null){
                root=root.right;
            }else{
                TreeNode pre=root.left;
                while(pre.right!=null){
                    pre=pre.right;
                }
                pre.right=root.right;
                root.right=root.left;
                root.left=null;
                root=root.right;
            }
        }
    }
}

相关文章

网友评论

      本文标题:114. 二叉树展开为链表

      本文链接:https://www.haomeiwen.com/subject/dzfcwhtx.html