二叉树转换成其他结构

将二叉树变为链表

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

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

思路:前序遍历树,将节点存储进来,遍历后连接各个节点。

public void flatten(TreeNode root) {
      Deque<TreeNode> deque = new ArrayDeque<TreeNode>();
      if(root != null) deque.add(root);
      TreeNode cur = null, tmp = null;
      while(!deque.isEmpty()){
            tmp = deque.pollLast();
            if(tmp.right != null) deque.add(tmp.right);
            if(tmp.left != null) deque.add(tmp.left);
            if(tmp != root){
                cur.right = tmp;
                cur.left = null;//不置为null会有问题。
            }
            cur = tmp;
      }
      if(tmp != null) tmp.right = null;
}

将二叉树同层节点相连

struct TreeLinkNode {
      TreeLinkNode left;
      TreeLinkNode right;
      TreeLinkNode next;
}

1.满二叉树
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
For example,
Given the following perfect binary tree,

        1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:

        1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

思路:递归做,如果是满二叉树,直接递归一层一层让左孩子连

public void connect(TreeLinkNode root) {
    TreeLinkNode start = root;
    while(start != null && start.left != null){
        TreeLinkNode p = start, q = new TreeLinkNode(0);
        while(p != null){
            q.next = p.left;
            p.left.next = p.right;
            q = p.right;
            p = p.next;
        }
        start = start.left;
    }
}

2.普通二叉树
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
For example,
Given the following binary tree,

        1
       / \
      2   3
     / \   \
    4   5   7

After calling your function, the tree should look like:

        1 -> NULL
       / \
      2 ->3 -> NULL
     / \   \
    4-> 5-> 7 -> NULL
public void connectII(TreeLinkNode root) {
        TreeLinkNode start = root;
        while(start != null){
            TreeLinkNode p = start, sonstart = new TreeLinkNode(0), q = sonstart;
            while(p != null){
                if(p.left != null){
                    q.next = p.left;
                    q = p.left;
                }
                if(p.right != null){
                    q.next = p.right;
                    q = p.right;
                }
                p = p.next;
            }   
            start = sonstart.next;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值