c++ 之字形打印树
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> res; if (pRoot == nullptr) return res; stack<TreeNode*> left; stack<TreeNode*> right; left.push(pRoot); int flag = 0;//flag为0 左栈出,进右栈 while (!left.empty() || !right.empty()){ vector<int> temp; if (flag == 0){ auto length = left.size(); for (decltype(length) i = 0; i != length; ++i){ if (left.top() != nullptr){ temp.push_back(left.top()->val); //vec记录 right.push(left.top()->left); right.push(left.top()->right); //子树进右栈 } left.pop(); //清空栈顶 } flag = 1; } else if (flag == 1){ auto length = right.size(); for (decltype(length) i = 0; i != length; ++i){ if (right.top() != nullptr){ temp.push_back(right.top()->val); //vec记录 left.push(right.top()->right); left.push(right.top()->left); //子树进左栈 } right.pop(); //清空栈顶 } flag = 0; } if (!temp.empty()) res.push_back(temp); } return res; } };
题目说之字形按层打印树,故考虑广度优先搜索。
1、因为要之字形打印,常规队列存储无法满足需求,采用两个栈(左栈和右栈),轮换存储的方式;
2、存储规则为左栈进栈时先右子后左子,右栈相反;初始化root放在左栈
欢迎交流指正!!!