1. 程式人生 > 其它 >LeetCode(面試題17.12)BiNode

LeetCode(面試題17.12)BiNode

雖然過了,但是還是不是很清楚,中序遍歷,訪問每個非空節點時,將左指標置空,pre記錄每個父節點,父節點的right置為當前節點

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* convertBiNode(TreeNode* root) {
        TreeNode
*p = root,*pre = NULL,*newroot; stack<TreeNode*>s; bool flag = true; while(p||!s.empty()){ if(p){ s.push(p); p = p->left; }else{ p = s.top(); if(flag&&p->left==NULL){ newroot
= p; flag = false; } p->left = NULL; if(pre)pre->right = p; cout<<p<<" "<<p->left<<" "<<p->right<<endl; s.pop(); pre = p; p
= p->right; } } return newroot; } };