zoukankan      html  css  js  c++  java
  • 二叉树 得到路径

    简介

    以前觉得这个问题还是挺难的. 后来发现其实也很简单. 直接上代码.

    code

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    #include <iostream>
    #include <vector>
    using namespace std;
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x): val(x), left(nullptr), right(nullptr){}
    };
        int level = 0;
        vector<TreeNode*> path1;
        vector<TreeNode*> path2;
        TreeNode* p;
        bool dfs(TreeNode *n, vector<TreeNode*> &path, TreeNode *p){
            if(n == p){
                path.push_back(n);
                return true;
            }
            if(n->left){
                if(dfs(n->left, path, p)){
                    path.push_back(n);
                    return true;
                }
            }
            if(n->right){
                if(dfs(n->right, path, p)){
                    path.push_back(n);
                    return true;
                }
            }
            return false;
        }
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            
        }
    int main(){
        TreeNode * a = new TreeNode(3);
        TreeNode * b = new TreeNode(5);
        TreeNode * c = new TreeNode(1);
        TreeNode * d = new TreeNode(6);
        TreeNode * e = new TreeNode(2);
        TreeNode * f = new TreeNode(0);
        TreeNode * g = new TreeNode(8);
        TreeNode * h = new TreeNode(7);
        TreeNode * i = new TreeNode(4);
        a->left = b;
        a->right = c;
        b->left = d;
        b->right = e;
        e->left = h;
        e->right = i;
        c->left = f;
        c->right = g;
        TreeNode * z = h;
        dfs(a, path1, z);
        for(auto it : path1){
            cout << it->val << std::endl;
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    73. Set Matrix Zeroes (Array)
    79. Word Search (Array; DFS,Back-Track)
    59. Spiral Matrix II (Array)
    PAT 1082. Read Number in Chinese
    PAT 1067 Sort with Swap(0,*)
    LeetCode Min Stack
    LeetCode Find Minimum In Rotated Sorted Array
    PAT 1071. Speech Patterns
    PAT 1022. Digital Library
    PAT 1041. Be Unique
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14801095.html
Copyright © 2011-2022 走看看