1. 程式人生 > >LeetCode-114.二叉樹展開為連結串列(相關話題:深度優先)

LeetCode-114.二叉樹展開為連結串列(相關話題:深度優先)

給定一個二叉樹,原地將它展開為連結串列。

例如,給定二叉樹

    1
   / \
  2   5
 / \   \
3   4   6

將其展開為:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

解題思路:

按照前序遍歷的順序(棧),展開成連結串列

Java程式碼:

/**
 * 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) {
        if(null == root)
            return;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while(null != p.left || null != p.right){
            if(null != p.left && null != p.right)
                stack.push(p.right);
            if(null != p.left){
                p.right = p.left;
                p.left = null;
            }

            p = p.right;
        }
        while(!stack.isEmpty()){
            TreeNode tmp = stack.pop();
            p.right = tmp;
            p = p.right;
            while(null != p.left || null != p.right){
                if(null != p.left && null != p.right)
                    stack.push(p.right);
                if(null != p.left){
                    p.right = p.left;
                    p.left = null;
                }

                p = p.right;
            }
        }
    }
}