LeetCode OJ - Flatten Binary Tree to Linked List
这题的提示中给出,linked list是原来二叉树的先序遍历。所以我用一个栈暂时存储每个节点的右子树(如果它有右子树的话),然后把左子树交换到右子树,左节点置为null,之后迭代下去,当遇到叶子节点时,从栈中pop出一个子树,再继续,直到遇到叶子节点且栈中为空。
下面是AC代码:
1 /** 2 * Given a binary tree, flatten it to a linked list in-place. 3 * If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. 4 * @param root 5 */ 6 public void flatten(TreeNode root){ 7 if(root == null || root.left==null && root.right == null) 8 return; 9 //the stack is for the right children 10 LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); 11 TreeNode temp = root; 12 while(true){ 13 if(temp.left!=null) 14 { 15 if(temp.right!=null) 16 stack.push(temp.right); 17 temp.right = temp.left; 18 temp.left = null; 19 20 } 21 if(temp.right != null) 22 temp = temp.right; 23 if(temp.left == null && temp.right == null){ 24 if(stack.isEmpty()) 25 break; 26 temp.right = stack.pop(); 27 temp = temp.right; 28 } 29 } 30 31 }
有问题可以和我联系,bettyting2010#163 dot com
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步