二叉樹遍歷

Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values. 中序遍歷


Input: [1,null,2,3]
1

2
/
3

Output: [1,3,2]

解法

遞歸

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

class Solution {
public:
      vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        inorder(root, res);
      return res;
    }
    void inorder(TreeNode *root, vector<int> &res) {
        if (!root) return;
        if (root->left) inorder(root->left, res);
        res.push_back(root->val);
        if (root->right) inorder(root->right, res);
    }
};

非遞歸

用棧來代替遞歸,簡歷二叉樹指針棧,儲存所有的遍歷的二叉樹節(jié)點(diǎn)。每次儲存后,中序遍歷移動指針到當(dāng)前左子節(jié)點(diǎn),直到遍歷到最左側(cè)葉子節(jié)點(diǎn),對于最左側(cè)葉子節(jié)點(diǎn),取當(dāng)前節(jié)點(diǎn)值,并指針移動到當(dāng)前節(jié)點(diǎn)右子節(jié)點(diǎn),棧中刪除當(dāng)前節(jié)點(diǎn)。循環(huán)直到棧為空并且指針指向空節(jié)點(diǎn)。(有左邊,去左邊,沒左邊,打印當(dāng)前,去最右邊。)
class Solution {
public:

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode* > s;
        TreeNode* p = root;
        while(p!= NULL || !s.empty()){
            if (p!=NULL){
                s.push(p);
                p = p->left;
            }else{
                res.push_back(s.top()->val);
                p = s.top()->right;
                s.pop();
            }
        }
        return res;
    }
};

Maximum Depth of Binary Tree

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        return max(maxDepth(root->left), maxDepth(root->right))+1;

    }
};

Minimum Depth of Binary Tree

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == NULL) return 0;
        if (root->left == NULL && (root->right == NULL) ) return 1; 
        if (root->left == NULL) return minDepth(root->right)+1;
        if (root->right == NULL) return minDepth(root->left)+1;
        return min(minDepth(root->left), minDepth(root->right))+1;

    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容