[leetcode]_Flatten Binary Tree to Linked List
题目:将一棵二叉树履平成一个类似Linked-list的东西。
思路:该过程类似于二叉树的前序遍历,但是遍历代码,我处理不来参数的变化。没AC。
-------->写的很好的解题博客
参考上述博客,思路很清楚的写出代码:
1 public void flatten(TreeNode root) { 2 if(root == null) return; 3 4 if(root.left != null){ 5 TreeNode leftNode = root.left; 6 TreeNode rightNode = root.right; 7 root.left = null; 8 root.right = leftNode; 9 10 while(leftNode.right != null) leftNode = leftNode.right; 11 leftNode.right = rightNode; 12 } 13 14 flatten(root.right); 15 16 }
采用前序遍历错误的代码:留在下方,回头来改正:
1 public void flatten(TreeNode root) { 2 if(root == null) return; 3 4 TreeNode newRoot = null , head = null; 5 Stack<TreeNode> s = new Stack<TreeNode>(); 6 7 while(root != null || !s.isEmpty()){ 8 while(root != null){ 9 10 //visit node 11 if(newRoot == null) { 12 newRoot = new TreeNode(root.val); 13 head = newRoot; 14 }else{ 15 newRoot.right = new TreeNode(root.val); 16 newRoot = newRoot.right; 17 } 18 19 s.push(root); 20 21 //visit leftChild 22 root = root.left; 23 } 24 if(!s.isEmpty()){ 25 26 //visit rightChild 27 root = s.pop(); 28 root = root.right; 29 } 30 } 31 root = head; 32 }