演算法題(三十七):按之字形順序列印二叉樹
阿新 • • 發佈:2018-11-24
題目描述
請實現一個函式按照之字形列印二叉樹,即第一行按照從左到右的順序列印,第二層按照從右至左的順序列印,第三行按照從左到右的順序列印,其他行以此類推。
分析
用兩個棧來實現,先把根結點放入s1,當行數為偶數時,s2從左到右放結點;當行數為奇數時,s1從右到左放結點;
筆者用java寫的程式不能100%AC,但c++卻可以,有大神可以指出來哪裡有問題嗎?
程式碼一
import java.util.ArrayList; import java.util.Stack; public class ZhiZiPrint { public static void main(String[] args) { // TODO Auto-generated method stub TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); TreeNode node7 = new TreeNode(7); TreeNode node8 = new TreeNode(8); node1.left = node3; node1.right = node2; node3.left = node4; node3.right = node5; node2.left = node6; node2.right = node7; node7.left = node8; ZhiZiPrint test = new ZhiZiPrint(); ArrayList<ArrayList<Integer> > lists = test.Print(node1); for(ArrayList<Integer> list: lists){ for(int num: list){ System.out.println(num); } } } public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { if(pRoot == null){ return null; } ArrayList<ArrayList<Integer> > lists = fun(pRoot); return lists; } public ArrayList<ArrayList<Integer>> fun(TreeNode root){ ArrayList<ArrayList<Integer> > lists = new ArrayList<>(); Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); s1.push(root); while(!s1.isEmpty() || !s2.isEmpty()){ if(!s1.isEmpty()){ ArrayList<Integer> list = new ArrayList<>(); int len1 = s1.size(); for(int i=0; i<len1; i++){ TreeNode node = s1.peek(); list.add(node.val); s1.pop(); if(node.left != null){ s2.push(node.left); } if(node.right != null){ s2.push(node.right); } } lists.add(list); } if(!s2.isEmpty()){ ArrayList<Integer> list = new ArrayList<>(); int len2 = s2.size(); for(int i=0; i<len2; i++){ TreeNode node = s2.pop(); list.add(node.val); if(node.right != null){ s1.push(node.right); } if(node.left != null){ s1.push(node.left); } } lists.add(list); } } return lists; } }
程式碼二(來源於牛客網)
連結:https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0 來源:牛客網 //思路2:利用兩個棧分別儲存奇數行和偶數行 class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> res; if(!pRoot)return res; stack<TreeNode*> sta1; //建立兩個棧,棧1用於存放奇數行節點,棧2用於存放偶數行節點 stack<TreeNode*> sta2; sta1.push(pRoot); vector<int> vec; //行容器,用於存入當前行輸出的結果 while(!sta1.empty()||!sta2.empty()){ if(sta2.empty()&&!sta1.empty()){ int len_1=sta1.size(); for(int i=0;i<len_1;i++){ TreeNode* tmp=sta1.top(); vec.push_back(tmp->val); sta1.pop(); if(tmp->left)sta2.push(tmp->left); //棧2存放偶數行節點,按照從左子節點到右子節點的順序push if(tmp->right)sta2.push(tmp->right); } res.push_back(vec); vec.clear(); } if(sta1.empty()&&!sta2.empty()){ int len_2=sta2.size(); for(int i=0;i<len_2;i++){ TreeNode* tmp=sta2.top(); vec.push_back(tmp->val); sta2.pop(); if(tmp->right)sta1.push(tmp->right); //棧1存放奇數行節點,按照從右子節點到左子節點的順序push if(tmp->left)sta1.push(tmp->left); } res.push_back(vec); vec.clear(); } } return res; } };