美文网首页
二叉树遍历

二叉树遍历

作者: joey_zhou | 来源:发表于2019-08-21 11:34 被阅读0次

    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);
        }
    };
    

    非递归

    用栈来代替递归,简历二叉树指针栈,储存所有的遍历的二叉树节点。每次储存后,中序遍历移动指针到当前左子节点,直到遍历到最左侧叶子节点,对于最左侧叶子节点,取当前节点值,并指针移动到当前节点右子节点,栈中删除当前节点。循环直到栈为空并且指针指向空节点。(有左边,去左边,没左边,打印当前,去最右边。)
    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;
    
        }
    };

    相关文章

      网友评论

          本文标题:二叉树遍历

          本文链接:https://www.haomeiwen.com/subject/ntdbsctx.html